// 视频播放器模块
// 播放视频
async function playVideo(video) {
    if (!video || !video.sources || !video.sources[0]) {
        console.error('无效的视频数据:', video);
        alert('视频数据无效，无法播放');
        return;
    }

    console.log('准备播放视频:', video.title, video.sources);
    currentVideo = video;

    // 根据清晰度优先级选择最优视频源
    let selectedSource = video.sources[0]; // 默认选择第一个

    if (video.sources.length > 1) {
        if (window.qualityPriorityHigh) {
            // 高清优先: 优先选择非720p的源
            selectedSource = video.sources.find(source => !source.filename.includes('720')) || video.sources[0];
        } else {
            // 流畅优先: 优先选择720p的源
            selectedSource = video.sources.find(source => source.filename.includes('720')) || video.sources[0];
        }
    }

    console.log('选择的视频源:', selectedSource);
    updateQualitySelector(video.sources);

    const sourceElement = document.getElementById('videoSource');
    const videoElement = document.getElementById('mainVideo');
    const playerElement = document.getElementById('player');

    if (!sourceElement || !videoElement) {
        console.error('找不到视频元素');
        alert('视频播放器初始化失败，请刷新页面');
        return;
    }

    try {
        // 尝试使用缓存的视频
        let videoUrl = `./videos/${encodeURIComponent(selectedSource.filename)}`;
        if (window.videoCache && window.videoCache.cacheEnabled) {
            try {
                const cachedUrl = await window.videoCache.getCachedVideo(selectedSource.filename);
                if (cachedUrl && cachedUrl !== videoUrl) {
                    videoUrl = cachedUrl;
                    console.log('使用缓存视频:', selectedSource.filename, '缓存URL:', videoUrl);
                }
            } catch (error) {
                console.warn('获取缓存视频失败，使用原始URL:', error);
            }
        }

        console.log('最终视频URL:', videoUrl);

        // 测试视频文件是否可访问（仅对非blob URL进行测试）
        if (!videoUrl.includes('blob:')) {
            let isAccessible = await testVideoAccessibility(videoUrl);

            // 如果主URL不可访问，尝试备用路径
            if (!isAccessible) {
                console.warn('主视频URL不可访问，尝试备用路径');

                // 为服务器环境提供多个备用路径
                const alternativeUrls = [
                    `./videos/${encodeURIComponent(selectedSource.filename)}`,
                    `videos/${encodeURIComponent(selectedSource.filename)}`,
                    `./videos/${selectedSource.filename}`,
                    `videos/${selectedSource.filename}`
                ];

                for (const altUrl of alternativeUrls) {
                    if (altUrl !== videoUrl) {
                        console.log('尝试备用URL:', altUrl);
                        isAccessible = await testVideoAccessibility(altUrl);
                        if (isAccessible) {
                            videoUrl = altUrl;
                            console.log('找到可访问的备用URL:', altUrl);
                            break;
                        }
                    }
                }
            }

            if (!isAccessible) {
                throw new Error(`所有视频路径都无法访问: ${selectedSource.filename}
请检查视频文件是否存在于videos文件夹中`);
            }
        }

        // 添加时间戳避免缓存问题
        const finalUrl = videoUrl.includes('blob:') ? videoUrl : `${videoUrl}?t=${Date.now()}`;

        sourceElement.src = finalUrl;
        videoElement.load();

        // 添加加载事件监听
        const loadPromise = new Promise((resolve, reject) => {
            const onCanPlay = () => {
                console.log('视频可以播放');
                videoElement.removeEventListener('canplay', onCanPlay);
                videoElement.removeEventListener('error', onError);
                resolve();
            };

            const onError = (event) => {
                console.error('视频加载错误:', event, videoElement.error);
                videoElement.removeEventListener('canplay', onCanPlay);
                videoElement.removeEventListener('error', onError);
                reject(new Error(`视频加载失败: ${videoElement.error?.message || '未知错误'}`));
            };

            videoElement.addEventListener('canplay', onCanPlay, { once: true });
            videoElement.addEventListener('error', onError, { once: true });

            // 10秒超时
            setTimeout(() => {
                videoElement.removeEventListener('canplay', onCanPlay);
                videoElement.removeEventListener('error', onError);
                reject(new Error('视频加载超时'));
            }, 10000);
        });

        try {
            await loadPromise;

            // 尝试播放
            await videoElement.play();
            console.log('视频播放成功');
        } catch (playError) {
            console.log('自动播放失败，需要用户交互:', playError);

            // 显示播放提示
            const playHint = document.createElement('div');
            playHint.className = 'play-hint';
            playHint.style.cssText = `
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: rgba(0,0,0,0.8);
                color: white;
                padding: 15px 25px;
                border-radius: 25px;
                cursor: pointer;
                font-size: 16px;
                z-index: 1000;
                backdrop-filter: blur(10px);
                border: 2px solid rgba(255,255,255,0.2);
            `;
            playHint.textContent = '🎬 点击播放视频';
            playerElement.appendChild(playHint);

            // 点击后开始播放
            playHint.onclick = async () => {
                try {
                    await videoElement.play();
                    playHint.remove();
                    console.log('用户点击后播放成功');
                } catch (error) {
                    console.error('用户点击播放仍然失败:', error);
                    playHint.textContent = '播放失败，请检查视频文件';
                }
            };
        } finally {
            // 显示播放器
            console.log('准备显示播放器...');
            if (playerElement) {
                // 清除之前的错误信息
                const existingError = playerElement.querySelector('.error-message');
                if (existingError) {
                    existingError.remove();
                    console.log('清除了之前的错误信息');
                }

                console.log('播放器元素存在，添加show类');
                playerElement.classList.add('show');
                console.log('播放器类列表:', playerElement.className);
            } else {
                console.error('播放器元素不存在！');
            }
        }

        // 记录视频播放日志
        if (window.accessLogger) {
            window.accessLogger.logVideoPlay(video.title);
        }

        // 检查当前视频的缓存状态
        setTimeout(() => {
            if (typeof window.checkCurrentVideoCacheStatus === 'function') {
                window.checkCurrentVideoCacheStatus();
            }
        }, 500);

    } catch (error) {
        console.error('视频播放失败:', error);

        // 即使出错也要显示播放器
        console.log('出错时也要显示播放器...');
        if (playerElement) {
            console.log('错误情况下显示播放器元素');
            playerElement.classList.add('show');
            console.log('错误时播放器类列表:', playerElement.className);
        }

        // 显示错误信息
        const videoElement = document.getElementById('mainVideo');
        if (videoElement && playerElement) {
            // 在播放器中显示错误信息
            const errorDiv = document.createElement('div');
            errorDiv.style.cssText = `
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: rgba(0,0,0,0.8);
                color: white;
                padding: 20px;
                border-radius: 10px;
                text-align: center;
                z-index: 1000;
                border: 2px solid #ff6b6b;
            `;
            errorDiv.innerHTML = `
                <h3>❌ 视频加载失败</h3>
                <p>${error.message}</p>
                <button onclick="location.reload()" style="margin-top: 10px; padding: 8px 16px; background: #ff6b6b; color: white; border: none; border-radius: 5px; cursor: pointer;">
                    刷新页面重试
                </button>
            `;

            // 清除之前的错误信息
            const existingError = playerElement.querySelector('.error-message');
            if (existingError) {
                existingError.remove();
            }

            errorDiv.className = 'error-message';
            playerElement.appendChild(errorDiv);
        }

        alert(`视频加载失败: ${error.message}
请检查视频文件是否存在，或刷新页面重试`);
    }
}

// 测试视频文件是否可访问
async function testVideoAccessibility(videoUrl) {
    try {
        console.log('测试视频可访问性:', videoUrl);
        const response = await fetch(videoUrl, {
            method: 'HEAD',
            cache: 'no-cache',
            mode: 'cors',
            credentials: 'same-origin'
        });

        if (response.ok) {
            console.log('视频文件可访问，状态:', response.status);
            return true;
        } else {
            console.warn('视频文件不可访问，状态:', response.status, response.statusText);
            return false;
        }
    } catch (error) {
        console.error('测试视频可访问性失败:', error);

        // 如果HEAD请求失败，尝试GET请求的范围请求
        try {
            const response = await fetch(videoUrl, {
                method: 'GET',
                headers: { 'Range': 'bytes=0-1' }, // 只请求前2个字节
                cache: 'no-cache',
                mode: 'cors',
                credentials: 'same-origin'
            });

            if (response.ok || response.status === 206) { // 206 是部分内容响应
                console.log('视频文件可访问（通过范围请求）');
                return true;
            }
        } catch (rangeError) {
            console.error('范围请求也失败:', rangeError);
        }

        return false;
    }
}

// 切换视频画质
async function changeVideoQuality(filename, clickedOption) {
    if (!filename || !currentVideo) return;

    const videoElement = document.getElementById('mainVideo');
    const sourceElement = document.getElementById('videoSource');

    if (sourceElement && videoElement) {
        // 更新选中状态
        document.querySelectorAll('.quality-option').forEach(option => {
            option.classList.remove('active');
        });
        if (clickedOption) {
            clickedOption.classList.add('active');
        }

        // 记住当前播放位置
        const currentTime = videoElement.currentTime;
        const wasPlaying = !videoElement.paused;

        // 尝试使用缓存的视频
        let videoUrl = `./videos/${encodeURIComponent(filename)}`;
        if (window.videoCache && window.videoCache.cacheEnabled) {
            try {
                const cachedUrl = await window.videoCache.getCachedVideo(filename);
                if (cachedUrl && cachedUrl !== videoUrl) {
                    videoUrl = cachedUrl;
                    console.log('切换画质时使用缓存视频:', filename);
                }
            } catch (error) {
                console.warn('获取缓存视频失败，使用原始URL:', error);
            }
        }

        // 更新视频源
        sourceElement.src = videoUrl;
        videoElement.load();

        // 恢复播放位置和状态
        videoElement.addEventListener('loadedmetadata', function onLoaded() {
            videoElement.currentTime = currentTime;
            if (wasPlaying) {
                videoElement.play();
            }
            videoElement.removeEventListener('loadedmetadata', onLoaded);
        }, { once: true });
    }
}

// 更新视频设置选项
function updateQualitySelector(sources) {
    const qualityOptions = document.getElementById('qualityOptions');
    if (!qualityOptions || !sources) return;

    // 获取当前正在播放的文件名
    const currentSource = document.getElementById('videoSource').src;
    const currentFilename = decodeURIComponent(currentSource.split('/').pop().split('?')[0]);

    // 根据清晰度优先级排序
    const sortedSources = [...sources].sort((a, b) => {
        const aIs720p = a.filename.includes('720');
        const bIs720p = b.filename.includes('720');

        if (window.qualityPriorityHigh) {
            // 高清优先: 非720p在前，720p在后
            if (aIs720p && !bIs720p) return 1;
            if (!aIs720p && bIs720p) return -1;
            return 0;
        } else {
            // 流畅优先: 720p在前，非720p在后
            if (aIs720p && !bIs720p) return -1;
            if (!aIs720p && bIs720p) return 1;
            return 0;
        }
    });

    qualityOptions.innerHTML = sortedSources.map(source => {
        const isActive = source.filename === currentFilename;
        const qualityText = source.quality === 'original' ? '原画' : source.quality;
        const resolution = getResolutionFromFilename(source.filename);

        return `
            <div class="quality-option ${isActive ? 'active' : ''}"
                 onclick="changeVideoQuality('${source.filename}', this)">
                ${qualityText}
                ${resolution ? `<span>${resolution}</span>` : ''}
            </div>
        `;
    }).join('');
}

// 从文件名推测分辨率
function getResolutionFromFilename(filename) {
    if (filename.includes('720')) return '720p';
    if (filename.includes('1080')) return '1080p';
    if (filename.includes('2k')) return '2K';
    if (filename.includes('4k')) return '4K';
    return '';
}

// 滚动到播放器
function scrollToPlayer() {
    console.log('scrollToPlayer 被调用');
    const player = document.getElementById('player');
    if (player) {
        console.log('找到播放器元素，准备滚动');
        console.log('播放器当前类:', player.className);

        setTimeout(() => {
            console.log('开始滚动到播放器');
            player.scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        }, 200); // 延迟200ms再跳转到播放器位置
    } else {
        console.error('找不到播放器元素！');
    }
}
