// UI渲染模块
// 渲染分类首页
function renderCategoryHome() {
    console.log('渲染分类首页，数据状态:', videoData ? '已加载' : '未加载');

    if (!videoData || !videoData.categories) {
        console.log('数据未准备好，显示加载状态');
        showCategoryLoading();
        return;
    }

    currentCategory = null;
    updateBreadcrumb();

    const categoryHome = document.getElementById('categoryHome');
    if (!categoryHome) return;

    categoryHome.innerHTML = videoData.categories.map(category => {
        const videoCount = category.videos ? category.videos.length : 0;
        const latestVideo = category.videos && category.videos.length > 0
            ? category.videos[category.videos.length - 1]
            : { title: '暂无视频' };

        return `
            <div class="category-card" onclick="showCategoryDetail('${category.id}')">
                <span class="icon">${category.icon}</span>
                <h3>${category.name}</h3>
                <p>${category.description}</p>
                <div class="stats">${videoCount} 个视频</div>
                <div class="latest">最新：${latestVideo.title}</div>
            </div>
        `;
    }).join('');

    console.log('分类首页渲染完成');
}

// 显示分类详情
function showCategoryDetail(categoryId) {
    if (!videoData || !videoData.categories) return;

    const category = videoData.categories.find(cat => cat.id === categoryId);
    if (!category) return;

    currentCategory = category;

    // 隐藏分类首页，显示详情页
    const categoryHome = document.getElementById('categoryHome');
    const categoryDetail = document.getElementById('categoryDetail');

    if (categoryHome) categoryHome.classList.add('hidden');
    if (categoryDetail) categoryDetail.classList.remove('hidden');

    // 更新面包屑
    updateBreadcrumb();

    // 渲染分类标题
    const categoryHeader = document.getElementById('categoryHeader');
    if (categoryHeader) {
        categoryHeader.innerHTML = `
            <span class="icon">${category.icon}</span>
            <h2>${category.name}</h2>
            <p>${category.description}</p>
            <div class="count">${category.videos ? category.videos.length : 0} 个视频</div>
        `;
    }

    // 渲染该分类的视频
    renderCategoryVideos(category.videos || []);
}

// 返回分类首页
function showCategoryHome() {
    const categoryDetail = document.getElementById('categoryDetail');
    const categoryHome = document.getElementById('categoryHome');

    if (categoryDetail) categoryDetail.classList.add('hidden');
    if (categoryHome) categoryHome.classList.remove('hidden');

    currentCategory = null;
    updateBreadcrumb();
}

// 渲染分类视频列表
function renderCategoryVideos(videos) {
    const categoryVideos = document.getElementById('categoryVideos');
    if (!categoryVideos) return;

    if (!videos || videos.length === 0) {
        categoryVideos.innerHTML = `
            <div style="grid-column: 1/-1; text-align: center; color: white; padding: 40px;">
                <h3>📭 该分类暂无视频</h3>
            </div>
        `;
        return;
    }

    categoryVideos.innerHTML = videos.map((video, index) => `
        <div class="video-item" data-index="${index}" data-mode="category">
            <h3>${video.title}</h3>
            <p>${video.description}</p>
            <div class="meta">
                <small>${video.sources && video.sources[0] ? video.sources[0].filename : ''}</small>
                <span class="duration">${video.sources && video.sources[0] ? video.sources[0].duration : ''}</span>
            </div>
        </div>
    `).join('');

    // 添加点击事件
    categoryVideos.querySelectorAll('.video-item').forEach(item => {
        item.addEventListener('click', function() {
            console.log('分类视频项被点击:', this.dataset.index);
            document.querySelectorAll('.video-item').forEach(i => i.classList.remove('active'));
            this.classList.add('active');

            const index = parseInt(this.dataset.index);
            console.log('准备播放分类视频，索引:', index, '视频:', videos[index]);

            // 确保播放器会显示（备用机制）
            setTimeout(() => {
                const player = document.getElementById('player');
                if (player && !player.classList.contains('show')) {
                    console.log('分类模式：播放器未显示，手动添加show类');
                    player.classList.add('show');
                }
            }, 100);

            playVideo(videos[index]);
            console.log('分类模式：调用scrollToPlayer');
            scrollToPlayer();
        });
    });

    // 应用当前的亮度样式到新渲染的video-item
    applyCurrentBrightnessStyle();
}

// 渲染传统模式
function renderOldMode() {
    if (!videoData || !videoData.categories) {
        showError('数据格式错误', '视频数据结构不正确');
        return;
    }

    // 将所有分类的视频合并
    const allVideos = [];
    videoData.categories.forEach(category => {
        if (category.videos && Array.isArray(category.videos)) {
            category.videos.forEach(video => {
                allVideos.push({
                    ...video,
                    categoryName: category.name,
                    categoryIcon: category.icon
                });
            });
        }
    });

    filteredVideos = [...allVideos];
    renderOldModeVideos();
}

// 渲染传统模式视频列表
function renderOldModeVideos() {
    const videoItems = document.getElementById('videoItems');
    if (!videoItems) return;

    if (!filteredVideos || filteredVideos.length === 0) {
        videoItems.innerHTML = `
            <div style="grid-column: 1/-1; text-align: center; color: white; padding: 40px;">
                <h3>🔍 没有找到匹配的视频</h3>
                <p>请尝试其他关键词</p>
            </div>
        `;
        return;
    }

    videoItems.innerHTML = filteredVideos.map((video, index) => `
        <div class="video-item" data-index="${index}" data-mode="old">
            <h3>${video.title}</h3>
            <p>${video.description}</p>
            <div class="meta">
                <small>${video.categoryIcon} ${video.categoryName}</small>
                <span class="duration">${video.sources && video.sources[0] ? video.sources[0].duration : ''}</span>
            </div>
        </div>
    `).join('');

    // 添加点击事件
    videoItems.querySelectorAll('.video-item').forEach(item => {
        item.addEventListener('click', function() {
            console.log('视频项被点击:', this.dataset.index);
            document.querySelectorAll('.video-item').forEach(i => i.classList.remove('active'));
            this.classList.add('active');

            const index = parseInt(this.dataset.index);
            console.log('准备播放视频，索引:', index, '视频:', filteredVideos[index]);

            // 确保播放器会显示（备用机制）
            setTimeout(() => {
                const player = document.getElementById('player');
                if (player && !player.classList.contains('show')) {
                    console.log('播放器未显示，手动添加show类');
                    player.classList.add('show');
                }
            }, 100);

            playVideo(filteredVideos[index]);
            console.log('调用scrollToPlayer');
            scrollToPlayer();
        });
    });

    // 应用当前的亮度样式到新渲染的video-item
    applyCurrentBrightnessStyle();
}

// 应用当前亮度样式到所有video-item
function applyCurrentBrightnessStyle() {
    const headerTitle = document.querySelector('header h1');
    const videoItems = document.querySelectorAll('.video-item');

    if (!headerTitle || videoItems.length === 0) return;

    // 根据标题的当前样式类来确定应该应用的video-item样式
    if (headerTitle.classList.contains('dark-bg')) {
        // 暗背景 - video-item使用浅色样式
        videoItems.forEach(item => {
            item.classList.remove('light-bg');
            item.classList.add('dark-bg');
        });
    } else if (headerTitle.classList.contains('light-bg')) {
        // 亮背景 - video-item使用深色样式
        videoItems.forEach(item => {
            item.classList.remove('dark-bg');
            item.classList.add('light-bg');
        });
    }
}

// 更新面包屑导航
function updateBreadcrumb() {
    const breadcrumb = document.getElementById('breadcrumb');
    if (!breadcrumb) return;

    if (currentCategory) {
        breadcrumb.innerHTML = `
            <a href="#" onclick="showCategoryHome()">🏠 首页</a>
            <span class="separator">></span>
            <span>${currentCategory.icon} ${currentCategory.name}</span>
        `;
    } else {
        breadcrumb.innerHTML = `
            <a href="#" onclick="showCategoryHome()">🏠 首页</a>
        `;
    }
}

// 显示分类加载状态
function showCategoryLoading() {
    const categoryHome = document.getElementById('categoryHome');
    showLoadingState(categoryHome, '📺 正在加载分类数据...（若长时间加载不出界面，请刷新界面）');
}

// 显示传统模式加载状态
function showOldModeLoading() {
    const videoItems = document.getElementById('videoItems');
    showLoadingState(videoItems, '📺 正在加载视频列表...');
}
