// 模式切换和导航模块
// 模式切换 - 简化版本（无动画）
function switchMode(mode) {
    console.log('切换模式到:', mode, '当前数据状态:', videoData ? '已加载' : '未加载');

    currentMode = mode;

    // 使用缓存的DOM元素
    const tagBtn = domCache.get('tagModeBtn');
    const oldBtn = domCache.get('oldModeBtn');
    const categoryHome = domCache.get('categoryHome');
    const categoryDetail = domCache.get('categoryDetail');
    const oldModeContainer = domCache.get('oldModeContainer');
    const breadcrumb = domCache.get('breadcrumb');

    // 批量更新按钮状态
    if (tagBtn) tagBtn.classList.toggle('active', mode === 'tag');
    if (oldBtn) oldBtn.classList.toggle('active', mode === 'old');

    // 直接切换内容，无动画
    if (mode === 'tag') {
        categoryHome?.classList.remove('hidden');
        categoryDetail?.classList.add('hidden');
        oldModeContainer?.classList.add('hidden');
        breadcrumb?.classList.remove('hidden');

        // 重置分类状态
        currentCategory = null;
        updateBreadcrumb();

        // 检查数据是否已加载
        if (videoData && videoData.categories) {
            renderCategoryHome();
        } else {
            showCategoryLoading();
        }
    } else {
        categoryHome?.classList.add('hidden');
        categoryDetail?.classList.add('hidden');
        oldModeContainer?.classList.remove('hidden');
        breadcrumb?.classList.add('hidden');

        // 检查数据是否已加载
        if (videoData && videoData.categories) {
            renderOldMode();
        } else {
            showOldModeLoading();
        }
    }

    // 保存用户选择
    localStorage.setItem('videoMode', mode);

    // 记录模式切换日志
    if (window.accessLogger) {
        window.accessLogger.logModeSwitch(mode);
    }
}

// 搜索功能 - 优化版本，添加防抖和缓存
const searchCache = new Map();
let searchAbortController = null;

function handleSearch(keyword) {
    // 取消之前的搜索请求（如果有的话）
    if (searchAbortController) {
        searchAbortController.abort();
    }
    searchAbortController = new AbortController();

    // 如果当前不是全部视频模式，切换到全部视频模式
    if (currentMode !== 'old') {
        switchMode('old');
    }

    if (!videoData || !videoData.categories) {
        return;
    }

    // 检查搜索缓存
    const cacheKey = keyword.trim().toLowerCase();
    if (searchCache.has(cacheKey)) {
        filteredVideos = searchCache.get(cacheKey);
        renderOldModeVideos();
        return;
    }

    // 获取所有视频（缓存结果）
    if (!window.allVideosCache) {
        window.allVideosCache = [];
        videoData.categories.forEach(category => {
            if (category.videos && Array.isArray(category.videos)) {
                category.videos.forEach(video => {
                    window.allVideosCache.push({
                        ...video,
                        categoryName: category.name,
                        categoryIcon: category.icon,
                        searchText: `${video.title} ${video.description} ${video.baseName || ''}`.toLowerCase()
                    });
                });
            }
        });
    }

    // 执行搜索
    try {
        if (cacheKey === '') {
            filteredVideos = [...window.allVideosCache];
        } else {
            // 使用预处理的搜索文本进行高效搜索
            filteredVideos = window.allVideosCache.filter(video =>
                video.searchText.includes(cacheKey)
            );
        }

        // 缓存搜索结果
        searchCache.set(cacheKey, filteredVideos);

        // 限制缓存大小
        if (searchCache.size > 50) {
            const firstKey = searchCache.keys().next().value;
            searchCache.delete(firstKey);
        }

        renderOldModeVideos();
    } catch (error) {
        if (error.name !== 'AbortError') {
            console.error('搜索失败:', error);
        }
    }
}

// 防抖搜索函数
const debouncedSearch = debounce(handleSearch, 300);

// 初始化搜索功能
function initializeSearch() {
    const searchInput = document.getElementById('searchInput');
    if (!searchInput) return;

    // 添加输入事件监听器，使用防抖优化性能
    searchInput.addEventListener('input', function(e) {
        const keyword = e.target.value.trim();
        debouncedSearch(keyword);
    });

    // 添加回车键监听
    searchInput.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
            const keyword = e.target.value.trim();
            handleSearch(keyword);
        }
    });

    console.log('搜索功能初始化完成');
}

// 键盘导航
function handleKeyboard(e) {
    const activeItem = document.querySelector('.video-item.active');
    if (!activeItem) return;

    const currentIndex = parseInt(activeItem.dataset.index);
    const mode = activeItem.dataset.mode;
    let items;

    if (mode === 'category') {
        items = document.getElementById('categoryVideos').querySelectorAll('.video-item');
    } else {
        items = document.getElementById('videoItems').querySelectorAll('.video-item');
    }

    if(e.key === 'ArrowUp' && currentIndex > 0) {
        items[currentIndex - 1].click();
    }
    if(e.key === 'ArrowDown' && currentIndex < items.length - 1) {
        items[currentIndex + 1].click();
    }
    if(e.key === 'Escape' && currentMode === 'tag' && currentCategory) {
        showCategoryHome();
    }
}

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

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

// 视频导航
function navigateVideo(direction) {
    const activeItem = document.querySelector('.video-item.active');
    if (!activeItem) return;

    const currentIndex = parseInt(activeItem.dataset.index);
    const mode = activeItem.dataset.mode;
    let items;

    if (mode === 'category') {
        items = document.getElementById('categoryVideos').querySelectorAll('.video-item');
    } else {
        items = document.getElementById('videoItems').querySelectorAll('.video-item');
    }

    let newIndex;
    if (direction === 'next') {
        newIndex = currentIndex < items.length - 1 ? currentIndex + 1 : 0;
    } else if (direction === 'prev') {
        newIndex = currentIndex > 0 ? currentIndex - 1 : items.length - 1;
    }

    if (items[newIndex]) {
        items[newIndex].click();
    }
}

// 更新画质选择器
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]);

    // 保持原始顺序，不进行排序

    qualityOptions.innerHTML = sources.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 '';
}
