// 数据加载模块
// 全局变量
let videoData = null;
let currentVideo = null;
let filteredVideos = [];
let currentMode = 'tag';
let currentCategory = null;

// DOM元素缓存 - 性能优化
const domCache = {
    elements: new Map(),
    get(id) {
        if (!this.elements.has(id)) {
            const element = document.getElementById(id);
            if (element) {
                this.elements.set(id, element);
            }
        }
        return this.elements.get(id) || null;
    },
    clear() {
        this.elements.clear();
    },
    invalidate(id) {
        this.elements.delete(id);
    }
};

// 加载视频数据
async function loadVideoData() {
    try {
        // 检测是否为本地开发环境 - 修复移动端访问问题
        const isLocalDev = window.location.hostname === 'localhost' ||
                          window.location.hostname === '127.0.0.1' ||
                          window.location.hostname.startsWith('192.168.') ||  // 局域网IP
                          window.location.hostname.startsWith('10.') ||       // 局域网IP
                          window.location.hostname.startsWith('172.') ||      // 局域网IP
                          window.location.protocol === 'file:' ||
                          window.location.port === '8000';                    // 开发服务器端口

        // 使用当前域名下的资源
        const timestamp = Date.now();
        const apiUrl = `${window.location.origin}/data/videos.json?t=${timestamp}`;
        console.log('使用当前域名的API:', apiUrl);

        const response = await fetch(apiUrl, {
            cache: 'no-cache',
            headers: {
                'Cache-Control': 'no-cache',
                'Pragma': 'no-cache'
            }
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();

        if (!data || !data.categories || !Array.isArray(data.categories)) {
            throw new Error('Invalid data structure');
        }

        videoData = data;

        // 确保根据当前模式正确渲染 - 关键修改
        console.log('数据加载完成，当前模式:', currentMode);
        if (currentMode === 'tag') {
            renderCategoryHome();
        } else if (currentMode === 'old') {
            renderOldMode();
        }

        console.log('视频数据加载成功:', videoData.categories.length, '个分类');
    } catch (error) {
        console.error('加载视频数据失败:', error);

        const isLocalDev = window.location.hostname === 'localhost' ||
                          window.location.hostname === '127.0.0.1' ||
                          window.location.hostname.startsWith('192.168.') ||
                          window.location.hostname.startsWith('10.') ||
                          window.location.hostname.startsWith('172.') ||
                          window.location.port === '8000';

        if (isLocalDev) {
            showError(
                '本地数据加载失败',
                `无法从 ${window.location.origin}/data/videos.json 加载数据。请确保文件存在且服务器正常运行。`
            );
        } else {
            showError('视频数据加载失败', '请检查网络连接或服务器状态');
        }

        loadFallbackData();
    }
}

// 备用数据加载（用于本地开发测试）
async function loadFallbackData() {
    console.log('尝试从当前域名加载数据...');

    try {
        const response = await fetch(`${window.location.origin}/data/videos.json`, {
            cache: 'no-cache',
            headers: {
                'Cache-Control': 'no-cache',
                'Pragma': 'no-cache'
            }
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();

        // 验证数据结构
        if (!data || !data.categories || !Array.isArray(data.categories)) {
            throw new Error('Invalid data structure');
        }

        videoData = data;

        // 根据当前模式初始化显示
        if (currentMode === 'tag') {
            renderCategoryHome();
        } else {
            renderOldMode();
        }

        console.log('本地数据加载成功:', videoData.categories.length, '个分类');

    } catch (error) {
        console.error('本地数据加载也失败:', error);

        // 如果本地也加载失败，显示离线示例数据
        const offlineData = {
            categories: [
                {
                    id: "example",
                    name: "示例分类",
                    description: "本地服务器数据加载失败，这是离线示例数据",
                    icon: "🎬",
                    videos: [
                        {
                            title: "示例视频1",
                            description: "请确保本地服务器运行正常，并且data/videos.json文件存在",
                            baseName: "example1",
                            sources: [
                                {
                                    quality: "720p",
                                    filename: "example1_720p.mp4",
                                    duration: "10:30"
                                }
                            ]
                        }
                    ]
                }
            ]
        };

        videoData = offlineData;

        // 根据当前模式初始化显示
        if (currentMode === 'tag') {
            renderCategoryHome();
        } else {
            renderOldMode();
        }

        // 显示错误提示
        showError(
            '本地数据加载失败',
            '请确保本地服务器运行在8000端口，并且data/videos.json文件存在'
        );
    }
}

// 显示加载状态
function showLoadingState(container, message = '正在加载...') {
    if (container) {
        container.innerHTML = `
            <div style="grid-column: 1/-1; text-align: center; color: white; padding: 40px;">
                <div class="video-loading">${message}</div>
            </div>
        `;
    }
}

// 显示错误信息
function showError(title, message) {
    const errorHtml = `
        <div style="grid-column: 1/-1; text-align: center; color: #ff6b6b; padding: 40px;">
            <h3>⚠️ ${title}</h3>
            <p>${message}</p>
            <button onclick="loadVideoData()" style="margin-top: 15px; padding: 8px 16px; background: #ff6b6b; color: white; border: none; border-radius: 4px; cursor: pointer;">重新加载</button>
        </div>
    `;

    const categoryHome = document.getElementById('categoryHome');
    const videoItems = document.getElementById('videoItems');

    if (currentMode === 'tag' && categoryHome) {
        categoryHome.innerHTML = errorHtml;
    } else if (videoItems) {
        videoItems.innerHTML = errorHtml;
    }
}
