<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ project.title }} - 分享演示</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            overflow: hidden;
            height: 100vh;
            color: white;
        }

        .presentation-container {
            position: relative;
            width: 100vw;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            background: radial-gradient(ellipse at center, rgba(255,255,255,0.1) 0%, rgba(0,0,0,0.3) 100%);
        }

        .slide-display {
            position: relative;
            width: 90vw;
            height: 90vh;
            max-width: calc(90vh * 16/9);
            max-height: calc(90vw * 9/16);
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.4);
            overflow: hidden;
            transition: all 0.3s ease;
        }

        /* 非全屏时悬停效果 */
        body:not(.fullscreen-mode) .slide-display:hover {
            transform: scale(1.02);
            box-shadow: 0 25px 80px rgba(0,0,0,0.5);
        }

        /* 全屏时占满整个屏幕 */
        .fullscreen-mode .slide-display {
            width: 100vw;
            height: 100vh;
            max-width: 100vw;
            max-height: 100vh;
            border-radius: 0;
            box-shadow: none;
        }

        .fullscreen-mode .slide-frame-container,
        .fullscreen-mode .slide-frame {
            border-radius: 0;
        }

        /* 幻灯片容器 - 支持多iframe缓存 */
        .slide-frame-container {
            position: relative;
            width: 100%;
            height: 100%;
            border-radius: 15px;
            overflow: hidden;
        }

        .slide-frame {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            border: none;
            border-radius: 15px;
            background: white;
            transition: opacity 0.3s ease;
        }

        .slide-frame.hidden {
            opacity: 0;
            pointer-events: none;
            z-index: 1;
        }

        .slide-frame.visible {
            opacity: 1;
            pointer-events: auto;
            z-index: 2;
        }

        /* 缓存的iframe样式 */
        .slide-frame.cached {
            display: block;
        }

        .slide-frame.not-loaded {
            display: none;
        }

        .presentation-controls {
            position: fixed;
            bottom: 30px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            gap: 20px;
            align-items: center;
            background: rgba(0,0,0,0.7);
            padding: 15px 25px;
            border-radius: 50px;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
            transition: opacity 0.3s ease, transform 0.3s ease;
            z-index: 1000;
        }

        /* 全屏时完全隐藏控制栏 */
        .fullscreen-mode .presentation-controls {
            display: none;
        }

        .control-btn {
            background: rgba(255,255,255,0.2);
            color: white;
            border: none;
            padding: 12px 18px;
            border-radius: 25px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 16px;
            display: flex;
            align-items: center;
            gap: 8px;
            min-width: 50px;
            justify-content: center;
        }

        .control-btn:hover {
            background: rgba(255,255,255,0.3);
            transform: translateY(-2px);
        }

        .control-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .slide-counter {
            color: white;
            font-size: 18px;
            font-weight: bold;
            padding: 0 15px;
            background: rgba(255,255,255,0.1);
            border-radius: 20px;
            padding: 8px 16px;
        }

        .presentation-header {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0,0,0,0.7);
            padding: 10px 20px;
            border-radius: 25px;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
            z-index: 1000;
            transition: opacity 0.3s ease, transform 0.3s ease;
        }

        /* 全屏时完全隐藏标题 */
        .fullscreen-mode .presentation-header {
            display: none;
        }

        .presentation-title {
            color: white;
            font-size: 18px;
            font-weight: bold;
            margin: 0;
        }

        .exit-btn {
            position: fixed;
            top: 20px;
            right: 20px;
            background: rgba(220,53,69,0.85);
            color: white;
            border: none;
            width: 46px;
            height: 46px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 20px;
            transition: all 0.3s ease;
            z-index: 1001;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
            backdrop-filter: blur(10px);
            border: 2px solid rgba(255,255,255,0.3);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .exit-btn:hover {
            background: rgba(220,53,69,1);
            transform: scale(1.15) rotate(90deg);
            box-shadow: 0 6px 20px rgba(220,53,69,0.5);
        }

        /* 全屏时完全隐藏退出按钮 */
        .fullscreen-mode .exit-btn {
            display: none;
        }

        .slide-thumbnails {
            position: fixed;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            display: flex;
            flex-direction: column;
            gap: 10px;
            max-height: 70vh;
            overflow-y: auto;
            background: rgba(0,0,0,0.5);
            padding: 15px;
            border-radius: 15px;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
            opacity: 0;
            transition: opacity 0.3s ease, transform 0.3s ease;
            z-index: 999;
        }

        .slide-thumbnails.show {
            opacity: 1;
        }

        /* 全屏时完全隐藏缩略图 */
        .fullscreen-mode .slide-thumbnails {
            display: none;
        }

        .thumbnail {
            width: 80px;
            height: 45px;
            border: 2px solid transparent;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s ease;
            overflow: hidden;
            background: white;
            position: relative;
        }

        .thumbnail:hover {
            border-color: #007bff;
            transform: scale(1.1);
        }

        .thumbnail.active {
            border-color: #28a745;
            box-shadow: 0 0 10px rgba(40, 167, 69, 0.5);
        }

        .thumbnail iframe {
            width: 100%;
            height: 100%;
            border: none;
            pointer-events: none;
            transform: scale(0.2);
            transform-origin: top left;
            width: 400px;
            height: 225px;
        }

        .thumbnail-number {
            position: absolute;
            bottom: 2px;
            right: 2px;
            background: rgba(0,0,0,0.7);
            color: white;
            font-size: 10px;
            padding: 2px 4px;
            border-radius: 3px;
        }

        .toggle-thumbnails {
            position: fixed;
            left: 20px;
            bottom: 30px;
            background: rgba(0,0,0,0.7);
            color: white;
            border: none;
            padding: 12px 15px;
            border-radius: 25px;
            cursor: pointer;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
            z-index: 1000;
        }

        .toggle-thumbnails:hover {
            background: rgba(0,0,0,0.9);
            transform: scale(1.05);
        }

        /* 全屏时完全隐藏缩略图切换按钮 */
        .fullscreen-mode .toggle-thumbnails {
            display: none;
        }

        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255,255,255,0.9);
            display: none; /* 默认隐藏，避免初始闪烁 */
            justify-content: center;
            align-items: center;
            border-radius: 15px;
            z-index: 10;
            transition: opacity 0.2s ease;
        }

        .loading-overlay.show {
            display: flex;
            opacity: 1;
        }

        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #007bff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 平滑过渡效果 */
        .slide-transition {
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        /* 防止iframe白屏闪烁 */
        iframe {
            background-color: white;
            will-change: opacity;
        }

        /* 硬件加速优化 */
        .slide-frame-container,
        .slide-frame {
            transform: translateZ(0);
            backface-visibility: hidden;
            perspective: 1000px;
        }

        /* 预加载优化 */
        .slide-frame.preloading {
            visibility: hidden;
            position: absolute;
            top: -9999px;
            left: -9999px;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .slide-display {
                width: 95vw;
                height: 95vh;
            }

            .presentation-controls {
                bottom: 15px;
                padding: 10px 15px;
                gap: 10px;
            }

            .control-btn {
                padding: 8px 12px;
                font-size: 14px;
            }

            .slide-counter {
                font-size: 14px;
                padding: 6px 12px;
            }

            .slide-thumbnails {
                left: 10px;
                padding: 10px;
            }

            .thumbnail {
                width: 60px;
                height: 34px;
            }

            .toggle-thumbnails {
                left: 10px;
                bottom: 15px;
                padding: 8px 12px;
            }
        }

        /* 键盘快捷键提示 */
        .keyboard-hints {
            position: fixed;
            top: 50%;
            right: 20px;
            transform: translateY(-50%);
            background: rgba(0,0,0,0.85);
            padding: 15px;
            border-radius: 10px;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
            opacity: 0;
            transition: opacity 0.3s ease, transform 0.3s ease;
            font-size: 12px;
            z-index: 1002;
        }

        .keyboard-hints.show {
            opacity: 1;
        }

        /* 全屏时也显示快捷键提示 */
        .fullscreen-mode .keyboard-hints.show {
            opacity: 1;
        }

        .keyboard-hints h6 {
            color: #007bff;
            margin-bottom: 10px;
        }

        .keyboard-hints div {
            margin-bottom: 5px;
        }

        .key {
            background: rgba(255,255,255,0.2);
            padding: 2px 6px;
            border-radius: 3px;
            font-family: monospace;
        }

        /* 缓存状态面板 */
        .cache-status {
            position: fixed;
            bottom: 80px;
            right: 20px;
            background: rgba(0,0,0,0.8);
            color: white;
            padding: 10px;
            border-radius: 8px;
            font-size: 11px;
            font-family: monospace;
            opacity: 0;
            transition: opacity 0.3s ease;
            z-index: 1000;
            min-width: 200px;
        }

        .cache-status.show {
            opacity: 1;
        }

        .cache-status h6 {
            color: #4caf50;
            margin: 0 0 8px 0;
            font-size: 12px;
        }

        .cache-status .stat-line {
            margin-bottom: 4px;
            display: flex;
            justify-content: space-between;
        }

        .cache-status .stat-value {
            color: #81c784;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="presentation-container">
        <!-- 演示标题 -->
        <div class="presentation-header">
            <h5 class="presentation-title">{{ project.title }}</h5>
        </div>

        <!-- 退出按钮 -->
        <button class="exit-btn" onclick="exitPresentation()" title="退出演示 (ESC)">
            <i class="fas fa-times"></i>
        </button>

        <!-- 主要幻灯片显示区域 -->
        <div class="slide-display">
            <div class="loading-overlay" id="loadingOverlay">
                <div class="loading-spinner"></div>
            </div>
            <div class="slide-frame-container" id="slideFrameContainer">
                <!-- iframe将动态创建和管理 -->
            </div>
        </div>

        <!-- 演示控制栏 -->
        <div class="presentation-controls">
            <button class="control-btn" id="prevBtn" onclick="previousSlide()" title="上一页 (←)">
                <i class="fas fa-chevron-left"></i>
            </button>
            
            <button class="control-btn" onclick="toggleAutoPlay()" id="autoPlayBtn" title="自动播放">
                <i class="fas fa-play"></i>
            </button>
            
            <div class="slide-counter" id="slideCounter">1 / {{ slides_count }}</div>
            
            <button class="control-btn" onclick="toggleFullscreen()" title="全屏 (F)">
                <i class="fas fa-expand"></i>
            </button>
            
            <button class="control-btn" id="nextBtn" onclick="nextSlide()" title="下一页 (→)">
                <i class="fas fa-chevron-right"></i>
            </button>
        </div>

        <!-- 缩略图切换按钮 -->
        <button class="toggle-thumbnails" onclick="toggleThumbnails()" title="显示/隐藏缩略图 (T)">
            <i class="fas fa-th-large"></i>
        </button>

        <!-- 幻灯片缩略图 -->
        <div class="slide-thumbnails" id="slideThumbnails">
            {% for slide in project.slides_data %}
            <div class="thumbnail {% if loop.index == 1 %}active{% endif %}" 
                 onclick="goToSlide({{ loop.index0 }})" 
                 data-slide-index="{{ loop.index0 }}">
                <iframe srcdoc="{{ slide.html_content | e }}" title="Slide {{ loop.index }}"></iframe>
                <div class="thumbnail-number">{{ loop.index }}</div>
            </div>
            {% endfor %}
        </div>

        <!-- 键盘快捷键提示 -->
        <div class="keyboard-hints" id="keyboardHints">
            <h6><i class="fas fa-keyboard"></i> 快捷键 & 操作</h6>
            <div><span class="key">←/→</span> 上一页/下一页</div>
            <div><span class="key">Space</span> 下一页</div>
            <div><span class="key">鼠标滚轮</span> 上下翻页</div>
            <div><span class="key">F</span> 全屏切换</div>
            <div><span class="key">T</span> 缩略图</div>
            <div><span class="key">H</span> 显示/隐藏帮助</div>
            <div><span class="key">C</span> 缓存状态</div>
            <div><span class="key">ESC</span> 退出演示</div>
        </div>

        <!-- 缓存状态面板 -->
        <div class="cache-status" id="cacheStatus">
            <h6><i class="fas fa-memory"></i> 缓存状态</h6>
            <div class="stat-line">
                <span>已缓存:</span>
                <span class="stat-value" id="cachedCount">0</span>
            </div>
            <div class="stat-line">
                <span>加载中:</span>
                <span class="stat-value" id="loadingCount">0</span>
            </div>
            <div class="stat-line">
                <span>缓存率:</span>
                <span class="stat-value" id="cacheRatio">0%</span>
            </div>
            <div class="stat-line">
                <span>总页数:</span>
                <span class="stat-value" id="totalCount">0</span>
            </div>
        </div>


    </div>

    <script>
        // 全局变量
        let currentSlideIndex = 0;
        let totalSlides = {{ slides_count }};
        let slidesData = {{ project.slides_data | tojson }};
        let autoPlayInterval = null;
        let isAutoPlaying = false;
        let thumbnailsVisible = false;
        let keyboardHintsVisible = false;

        // 缓存机制相关变量
        let slideFrameCache = new Map(); // 缓存已渲染的iframe: slideIndex -> iframe元素
        let currentVisibleFrame = null; // 当前显示的iframe
        let isTransitioning = false; // 是否正在切换中
        let loadingSlides = new Set(); // 正在加载的幻灯片索引
        let frameIdCounter = 0; // iframe ID计数器

        // 初始化演示
        document.addEventListener('DOMContentLoaded', function() {
            initializePresentation();
            updateControls();

            // 启动定期检查数据更新
            startDataRefreshCheck();
        });

        // 初始化演示系统
        function initializePresentation() {
            // 加载第一张幻灯片
            loadSlideWithCache(0, true);

            // 预加载前几张幻灯片以提升体验
            setTimeout(() => {
                preloadAdjacentSlides(0);
            }, 1000);
        }

        // 定期检查数据更新
        function startDataRefreshCheck() {
            setInterval(async () => {
                try {
                    const response = await fetch(`/api/projects/{{ project.project_id }}/slides-data`);
                    const data = await response.json();

                    if (data.status === 'success' && data.updated_at > {{ project.updated_at }}) {
                        // 数据已更新，刷新幻灯片数据
                        slidesData = data.slides_data;
                        totalSlides = data.total_slides;

                        // 清空所有缓存
                        clearAllCache();

                        // 重新加载当前幻灯片
                        loadSlideWithCache(currentSlideIndex, true);

                        // 更新缩略图
                        updateThumbnailsContent();

                        // 显示更新提示
                        showUpdateNotification();
                    }
                } catch (error) {
                    // 检查数据更新失败
                }
            }, 10000); // 每10秒检查一次
        }

        // 更新缩略图内容
        function updateThumbnailsContent() {
            const thumbnailsContainer = document.getElementById('slideThumbnails');
            thumbnailsContainer.innerHTML = '';

            slidesData.forEach((slide, index) => {
                const thumbnailDiv = document.createElement('div');
                thumbnailDiv.className = `thumbnail ${index === currentSlideIndex ? 'active' : ''}`;
                thumbnailDiv.onclick = () => goToSlide(index);
                thumbnailDiv.setAttribute('data-slide-index', index);

                thumbnailDiv.innerHTML = `
                    <iframe srcdoc="${slide.html_content.replace(/"/g, '&quot;')}" title="Slide ${index + 1}"></iframe>
                    <div class="thumbnail-number">${index + 1}</div>
                `;

                thumbnailsContainer.appendChild(thumbnailDiv);
            });
        }

        // 显示更新通知
        function showUpdateNotification() {
            const notification = document.createElement('div');
            notification.style.cssText = `
                position: fixed;
                top: 80px;
                right: 20px;
                background: rgba(40, 167, 69, 0.9);
                color: white;
                padding: 10px 15px;
                border-radius: 5px;
                z-index: 2000;
                font-size: 14px;
                backdrop-filter: blur(10px);
                border: 1px solid rgba(255,255,255,0.2);
            `;
            notification.innerHTML = '<i class="fas fa-sync"></i> 幻灯片内容已更新';

            document.body.appendChild(notification);

            setTimeout(() => {
                notification.remove();
            }, 3000);
        }

        // 使用缓存机制加载幻灯片
        function loadSlideWithCache(index, isInitial = false) {
            if (index < 0 || index >= totalSlides || isTransitioning) return;

            // 如果是相同的幻灯片，直接返回
            if (index === currentSlideIndex && !isInitial) return;

            isTransitioning = true;

            // 检查是否已缓存
            if (slideFrameCache.has(index)) {
                // 使用缓存的iframe
                const cachedFrame = slideFrameCache.get(index);
                switchToFrame(cachedFrame, index);
            } else {
                // 创建新的iframe并渲染
                createAndLoadFrame(index, isInitial);
            }
        }

        // 创建并加载新的iframe
        function createAndLoadFrame(index, isInitial = false) {
            if (loadingSlides.has(index)) return; // 防止重复加载

            loadingSlides.add(index);

            if (isInitial) {
                showLoadingOverlay();
            }

            const frameId = `slideFrame_${frameIdCounter++}`;
            const iframe = document.createElement('iframe');
            iframe.id = frameId;
            iframe.className = 'slide-frame hidden not-loaded';
            iframe.title = `PPT Slide ${index + 1}`;

            // 设置内容
            if (slidesData[index] && slidesData[index].html_content) {
                iframe.srcdoc = slidesData[index].html_content;

                // 监听加载完成
                iframe.onload = function() {
                    // 缓存iframe
                    slideFrameCache.set(index, iframe);
                    loadingSlides.delete(index);

                    // 更新样式
                    iframe.classList.remove('not-loaded');
                    iframe.classList.add('cached');

                    // 延迟一点确保内容完全渲染
                    setTimeout(() => {
                        switchToFrame(iframe, index);
                    }, 100);
                };

                iframe.onerror = function() {
                    loadingSlides.delete(index);
                    isTransitioning = false;
                    hideLoadingOverlay();
                };

                // 添加到容器
                document.getElementById('slideFrameContainer').appendChild(iframe);
            } else {
                loadingSlides.delete(index);
                isTransitioning = false;
                hideLoadingOverlay();
            }
        }

        // 切换到指定的iframe
        function switchToFrame(targetFrame, index) {
            // 隐藏当前显示的iframe
            if (currentVisibleFrame) {
                currentVisibleFrame.classList.remove('visible');
                currentVisibleFrame.classList.add('hidden');
            }

            // 显示目标iframe
            targetFrame.classList.remove('hidden');
            targetFrame.classList.add('visible');

            // 更新状态
            currentVisibleFrame = targetFrame;
            currentSlideIndex = index;
            isTransitioning = false;

            // 更新UI
            updateControls();
            updateThumbnails();
            hideLoadingOverlay();

            // 预加载相邻幻灯片
            setTimeout(() => {
                preloadAdjacentSlides(index);
                // 管理缓存大小
                manageCacheSize();
            }, 300);
        }

        // 预加载相邻幻灯片
        function preloadAdjacentSlides(currentIndex) {
            const preloadIndices = [];

            // 预加载策略：当前页前后各2页
            for (let i = Math.max(0, currentIndex - 2); i <= Math.min(totalSlides - 1, currentIndex + 2); i++) {
                if (i !== currentIndex && !slideFrameCache.has(i) && !loadingSlides.has(i)) {
                    preloadIndices.push(i);
                }
            }

            // 分批预加载，避免同时加载太多
            preloadIndices.forEach((index, i) => {
                setTimeout(() => {
                    preloadSlide(index);
                }, i * 200); // 每200ms预加载一个
            });
        }

        // 预加载单个幻灯片
        function preloadSlide(index) {
            if (index < 0 || index >= totalSlides || slideFrameCache.has(index) || loadingSlides.has(index)) {
                return;
            }

            loadingSlides.add(index);

            const frameId = `slideFrame_${frameIdCounter++}`;
            const iframe = document.createElement('iframe');
            iframe.id = frameId;
            iframe.className = 'slide-frame hidden not-loaded';
            iframe.title = `PPT Slide ${index + 1}`;

            if (slidesData[index] && slidesData[index].html_content) {
                iframe.srcdoc = slidesData[index].html_content;

                iframe.onload = function() {
                    slideFrameCache.set(index, iframe);
                    loadingSlides.delete(index);

                    iframe.classList.remove('not-loaded');
                    iframe.classList.add('cached');
                };

                iframe.onerror = function() {
                    loadingSlides.delete(index);
                };

                // 添加到容器
                document.getElementById('slideFrameContainer').appendChild(iframe);
            } else {
                loadingSlides.delete(index);
            }
        }

        // 显示加载动画
        function showLoadingOverlay() {
            const loadingOverlay = document.getElementById('loadingOverlay');
            loadingOverlay.classList.add('show');
        }

        // 隐藏加载动画
        function hideLoadingOverlay() {
            const loadingOverlay = document.getElementById('loadingOverlay');
            loadingOverlay.classList.remove('show');
        }

        // 清空所有缓存
        function clearAllCache() {
            // 移除所有缓存的iframe
            slideFrameCache.forEach((iframe, index) => {
                if (iframe.parentNode) {
                    iframe.parentNode.removeChild(iframe);
                }
            });

            // 清空缓存映射
            slideFrameCache.clear();
            loadingSlides.clear();
            currentVisibleFrame = null;
        }

        // 获取缓存统计信息
        function getCacheStats() {
            return {
                cachedSlides: slideFrameCache.size,
                loadingSlides: loadingSlides.size,
                totalSlides: totalSlides,
                cacheRatio: (slideFrameCache.size / totalSlides * 100).toFixed(1) + '%'
            };
        }

        // 智能缓存管理 - 限制缓存数量以节省内存
        function manageCacheSize() {
            const maxCacheSize = Math.min(10, totalSlides); // 最多缓存10个幻灯片

            if (slideFrameCache.size > maxCacheSize) {
                // 移除距离当前页面最远的缓存
                const sortedIndices = Array.from(slideFrameCache.keys()).sort((a, b) => {
                    const distA = Math.abs(a - currentSlideIndex);
                    const distB = Math.abs(b - currentSlideIndex);
                    return distB - distA; // 距离远的排在前面
                });

                // 移除最远的缓存
                const toRemove = sortedIndices.slice(0, slideFrameCache.size - maxCacheSize + 1);
                toRemove.forEach(index => {
                    const iframe = slideFrameCache.get(index);
                    if (iframe && iframe !== currentVisibleFrame) {
                        if (iframe.parentNode) {
                            iframe.parentNode.removeChild(iframe);
                        }
                        slideFrameCache.delete(index);
                    }
                });
            }
        }

        // 兼容旧的loadSlide函数
        function loadSlide(index) {
            loadSlideWithCache(index);
        }

        // 更新控制按钮状态
        function updateControls() {
            const prevBtn = document.getElementById('prevBtn');
            const nextBtn = document.getElementById('nextBtn');
            const slideCounter = document.getElementById('slideCounter');

            prevBtn.disabled = currentSlideIndex === 0;
            nextBtn.disabled = currentSlideIndex === totalSlides - 1;
            slideCounter.textContent = `${currentSlideIndex + 1} / ${totalSlides}`;
        }

        // 更新缩略图状态
        function updateThumbnails() {
            const thumbnails = document.querySelectorAll('.thumbnail');
            thumbnails.forEach((thumb, index) => {
                thumb.classList.toggle('active', index === currentSlideIndex);
            });
        }

        // 上一页
        function previousSlide() {
            if (currentSlideIndex > 0 && !isTransitioning) {
                loadSlideWithCache(currentSlideIndex - 1);
            }
        }

        // 下一页
        function nextSlide() {
            if (currentSlideIndex < totalSlides - 1 && !isTransitioning) {
                loadSlideWithCache(currentSlideIndex + 1);
            }
        }

        // 跳转到指定幻灯片
        function goToSlide(index) {
            if (!isTransitioning && index !== currentSlideIndex && index >= 0 && index < totalSlides) {
                loadSlideWithCache(index);
            }
        }

        // 切换自动播放
        function toggleAutoPlay() {
            const autoPlayBtn = document.getElementById('autoPlayBtn');

            if (isAutoPlaying) {
                clearInterval(autoPlayInterval);
                autoPlayBtn.innerHTML = '<i class="fas fa-play"></i>';
                autoPlayBtn.title = '自动播放';
                isAutoPlaying = false;
            } else {
                autoPlayInterval = setInterval(() => {
                    if (currentSlideIndex < totalSlides - 1) {
                        nextSlide();
                    } else {
                        // 到达最后一页，停止自动播放
                        toggleAutoPlay();
                    }
                }, 5000); // 5秒间隔

                autoPlayBtn.innerHTML = '<i class="fas fa-pause"></i>';
                autoPlayBtn.title = '暂停自动播放';
                isAutoPlaying = true;
            }
        }

        // 全屏模式控制相关
        let isFullscreenMode = false;

        // 切换全屏
        function toggleFullscreen() {
            if (!document.fullscreenElement) {
                document.documentElement.requestFullscreen().catch(err => {
                    // 无法进入全屏模式
                });
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                }
            }
        }

        // 切换缩略图显示
        function toggleThumbnails() {
            const thumbnails = document.getElementById('slideThumbnails');
            thumbnailsVisible = !thumbnailsVisible;
            thumbnails.classList.toggle('show', thumbnailsVisible);
        }

        // 切换键盘快捷键提示
        function toggleKeyboardHints() {
            const hints = document.getElementById('keyboardHints');
            keyboardHintsVisible = !keyboardHintsVisible;
            hints.classList.toggle('show', keyboardHintsVisible);
        }

        // 切换缓存状态显示
        let cacheStatusVisible = false;
        function toggleCacheStatus() {
            const cacheStatus = document.getElementById('cacheStatus');
            cacheStatusVisible = !cacheStatusVisible;
            cacheStatus.classList.toggle('show', cacheStatusVisible);

            if (cacheStatusVisible) {
                updateCacheStatusDisplay();
                // 定期更新缓存状态
                const updateInterval = setInterval(() => {
                    if (cacheStatusVisible) {
                        updateCacheStatusDisplay();
                    } else {
                        clearInterval(updateInterval);
                    }
                }, 1000);
            }
        }

        // 更新缓存状态显示
        function updateCacheStatusDisplay() {
            const stats = getCacheStats();
            document.getElementById('cachedCount').textContent = stats.cachedSlides;
            document.getElementById('loadingCount').textContent = stats.loadingSlides;
            document.getElementById('cacheRatio').textContent = stats.cacheRatio;
            document.getElementById('totalCount').textContent = stats.totalSlides;
        }

        // 退出演示
        function exitPresentation() {
            // 停止自动播放
            if (isAutoPlaying) {
                toggleAutoPlay();
            }

            // 退出全屏
            if (document.fullscreenElement) {
                document.exitFullscreen();
            }

            // 关闭浏览器标签页
            window.close();
        }

        // 键盘事件处理（防抖）
        let keyboardDebounce = false;
        document.addEventListener('keydown', function(e) {
            // 防止在切换过程中重复触发
            if (isTransitioning) return;

            // 使用 keyCode 作为备选方案，确保兼容性
            const key = e.key || String.fromCharCode(e.keyCode);

            switch(e.key) {
                case 'ArrowLeft':
                    e.preventDefault();
                    if (!keyboardDebounce) {
                        keyboardDebounce = true;
                        previousSlide();
                        setTimeout(() => keyboardDebounce = false, 200);
                    }
                    break;
                case 'ArrowRight':
                case ' ':
                    e.preventDefault();
                    if (!keyboardDebounce) {
                        keyboardDebounce = true;
                        nextSlide();
                        setTimeout(() => keyboardDebounce = false, 200);
                    }
                    break;
                case 'f':
                case 'F':
                    e.preventDefault();
                    toggleFullscreen();
                    break;
                case 't':
                case 'T':
                    e.preventDefault();
                    if (!isFullscreenMode) {
                        toggleThumbnails();
                    }
                    break;
                case 'h':
                case 'H':
                    e.preventDefault();
                    toggleKeyboardHints();
                    break;
                case 'c':
                case 'C':
                    e.preventDefault();
                    toggleCacheStatus();
                    break;
                case 'Escape':
                    e.preventDefault();
                    exitPresentation();
                    break;
                case 'Home':
                    e.preventDefault();
                    if (!keyboardDebounce) {
                        keyboardDebounce = true;
                        goToSlide(0);
                        setTimeout(() => keyboardDebounce = false, 200);
                    }
                    break;
                case 'End':
                    e.preventDefault();
                    if (!keyboardDebounce) {
                        keyboardDebounce = true;
                        goToSlide(totalSlides - 1);
                        setTimeout(() => keyboardDebounce = false, 200);
                    }
                    break;
            }
        }, true); // 使用捕获阶段，确保事件优先处理

        // 鼠标滚轮事件（防抖）- 优化灵敏度
        let wheelDebounce = false;
        let wheelTimeout = null;
        document.addEventListener('wheel', function(e) {
            // 检查是否在缩略图上滚动
            const thumbnails = document.getElementById('slideThumbnails');
            if (thumbnails && thumbnails.classList.contains('show') && e.target.closest('.slide-thumbnails')) {
                // 允许缩略图区域正常滚动
                return;
            }

            if (isTransitioning || wheelDebounce) return;

            e.preventDefault();
            e.stopPropagation();
            wheelDebounce = true;

            // 向下滚动翻到下一页，向上滚动翻到上一页
            if (e.deltaY > 0) {
                nextSlide();
            } else if (e.deltaY < 0) {
                previousSlide();
            }

            // 使用较短的防抖时间，提升响应速度
            setTimeout(() => wheelDebounce = false, 400);
        }, { passive: false, capture: true });

        // 触摸事件支持（移动设备）
        let touchStartX = 0;
        let touchEndX = 0;
        let touchDebounce = false;

        document.addEventListener('touchstart', function(e) {
            if (isTransitioning) return;
            touchStartX = e.changedTouches[0].screenX;
        });

        document.addEventListener('touchend', function(e) {
            if (isTransitioning || touchDebounce) return;
            touchEndX = e.changedTouches[0].screenX;
            handleSwipe();
        });

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

            if (Math.abs(diff) > swipeThreshold) {
                touchDebounce = true;

                if (diff > 0) {
                    // 向左滑动，下一页
                    nextSlide();
                } else {
                    // 向右滑动，上一页
                    previousSlide();
                }

                setTimeout(() => touchDebounce = false, 300);
            }
        }

        // 全屏状态变化监听
        document.addEventListener('fullscreenchange', function() {
            const fullscreenBtn = document.querySelector('[onclick="toggleFullscreen()"]');
            if (document.fullscreenElement) {
                // 进入全屏模式
                if (fullscreenBtn) {
                    fullscreenBtn.innerHTML = '<i class="fas fa-compress"></i>';
                    fullscreenBtn.title = '退出全屏';
                }
                document.body.classList.add('fullscreen-mode');
                isFullscreenMode = true;
            } else {
                // 退出全屏模式
                if (fullscreenBtn) {
                    fullscreenBtn.innerHTML = '<i class="fas fa-expand"></i>';
                    fullscreenBtn.title = '全屏';
                }
                document.body.classList.remove('fullscreen-mode');
                isFullscreenMode = false;
            }
        });

        // 防止右键菜单
        document.addEventListener('contextmenu', function(e) {
            e.preventDefault();
        }, true);

        // 防止点击事件干扰键盘事件
        document.addEventListener('click', function(e) {
            // 确保焦点在文档上，以便键盘事件正常工作
            if (document.activeElement && document.activeElement.tagName === 'IFRAME') {
                document.body.focus();
            }
        }, true);

        // 页面加载完成后立即获取焦点
        window.addEventListener('load', function() {
            document.body.setAttribute('tabindex', '-1');
            document.body.focus();
        });

        // 页面可见性变化时暂停自动播放
        document.addEventListener('visibilitychange', function() {
            if (document.hidden && isAutoPlaying) {
                toggleAutoPlay();
            }
        });
    </script>
</body>
</html>
