// 工具函数 - 防抖和节流
const debounce = (func, wait) => {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func.apply(this, args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
};

const throttle = (func, limit) => {
    let inThrottle;
    return function(...args) {
        if (!inThrottle) {
            func.apply(this, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
};

// 检测本地开发环境的工具函数
function isLocalDevelopment() {
    return 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';                    // 开发服务器端口
}

// 获取正确的API URL - 通用版本
function getApiUrl(relativePath) {
    // 始终使用当前域名，确保在任何环境下都能正常工作
    return `${window.location.origin}${relativePath}`;
}

// 获取音效文件URL
function getSoundUrl(filename) {
    // 使用getApiUrl函数获取音效URL，确保通用性
    // 音效文件实际存储在background目录中
    return getApiUrl(`/background/${filename}`);
}

// 优化触摸手势支持
let isTouching = false;
let touchStartX = 0;
let touchEndX = 0;

const handleTouchStart = (e) => {
    if (e.touches.length === 1) {
        touchStartX = e.touches[0].screenX;
        isTouching = true;
    }
};

const handleTouchEnd = (e) => {
    if (!isTouching || e.changedTouches.length !== 1) return;

    touchEndX = e.changedTouches[0].screenX;
    isTouching = false;
    handleSwipe();
};

// 添加事件监听器（被动监听以提高性能）
document.addEventListener('touchstart', handleTouchStart, { passive: true });
document.addEventListener('touchend', handleTouchEnd, { passive: true });

function handleSwipe() {
    const swipeThreshold = 50;
    const diff = touchStartX - touchEndX;

    if (Math.abs(diff) > swipeThreshold) {
        if (diff > 0) {
            // 向左滑动 - 下一个视频
            navigateVideo('next');
        } else {
            // 向右滑动 - 上一个视频
            navigateVideo('prev');
        }
    }
}
