{% extends "base.html" %}

{% block title %}{{ project.title }} - 项目详情 - LandPPT{% endblock %}

{% block extra_css %}
<style>
/* 现代化项目详情页面 */
.project-detail-hero {
    background: var(--glass-bg);
    backdrop-filter: blur(30px);
    border: 1px solid var(--glass-border);
    color: var(--text-primary);
    padding: var(--spacing-2xl) var(--spacing-lg);
    margin: calc(-1 * var(--spacing-lg)) calc(-1 * var(--spacing-lg)) var(--spacing-2xl) calc(-1 * var(--spacing-lg));
    text-align: center;
    position: relative;
    overflow: hidden;
    border-radius: 0 0 var(--border-radius-xl) var(--border-radius-xl);
}

.project-detail-hero::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background:
        radial-gradient(circle at 20% 30%, rgba(52, 152, 219, 0.1) 0%, transparent 50%),
        radial-gradient(circle at 80% 70%, rgba(155, 89, 182, 0.1) 0%, transparent 50%);
    animation: projectDetailFloat 22s ease-in-out infinite;
}

@keyframes projectDetailFloat {
    0%, 100% { transform: scale(1) rotate(0deg); }
    50% { transform: scale(1.02) rotate(-1deg); }
}

.project-detail-hero h2 {
    font-size: 2.2rem;
    font-weight: 700;
    margin-bottom: var(--spacing-md);
    background: var(--primary-gradient);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    position: relative;
    z-index: 1;
    letter-spacing: -0.02em;
}

.project-detail-hero p {
    font-size: 1.1rem;
    color: var(--text-secondary);
    margin: 0;
    position: relative;
    z-index: 1;
    font-weight: 500;
}

.project-detail-hero code {
    background: var(--glass-bg);
    backdrop-filter: blur(10px);
    border: 1px solid var(--glass-border);
    padding: var(--spacing-xs) var(--spacing-md);
    border-radius: var(--border-radius-sm);
    font-family: 'Consolas', monospace;
    color: var(--text-primary);
}

/* 状态指示器美化 */
.status-indicator {
    width: 70px;
    height: 70px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 2.5rem;
    margin-right: var(--spacing-xl);
    box-shadow: 0 8px 25px rgba(0,0,0,0.2);
    position: relative;
}

.status-indicator::before {
    content: '';
    position: absolute;
    top: -3px;
    left: -3px;
    right: -3px;
    bottom: -3px;
    border-radius: 50%;
    background: linear-gradient(45deg, rgba(255,255,255,0.3), transparent);
    z-index: -1;
}

.status-indicator.completed {
    background: var(--success-gradient);
}

.status-indicator.in_progress {
    background: var(--accent-gradient);
}

.status-indicator.draft {
    background: linear-gradient(135deg, #95a5a6, #7f8c8d);
}

.status-indicator.error {
    background: var(--secondary-gradient);
}

/* 项目信息卡片美化 */
.project-info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: var(--spacing-lg);
    background: var(--glass-bg);
    backdrop-filter: blur(15px);
    border: 1px solid var(--glass-border);
    padding: var(--spacing-xl);
    border-radius: var(--border-radius-lg);
    margin-bottom: var(--spacing-xl);
}

.project-info-item {
    text-align: center;
}

.project-info-item strong {
    display: block;
    color: var(--text-secondary);
    font-size: 0.9rem;
    margin-bottom: var(--spacing-xs);
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.project-info-item p {
    color: var(--text-primary);
    font-weight: 600;
    font-size: 1.1rem;
    margin: 0;
}
</style>
{% endblock %}

{% block content %}
<div class="project-detail-hero">
    <h2>{{ project.title }}</h2>
    <p>项目ID: <code>{{ project.project_id }}</code></p>
</div>

<div style="max-width: 1400px; margin: 0 auto; padding: var(--spacing-lg);">`

<div class="grid">
    <!-- Project Information -->
    <div class="card">
        <h3 style="color: #3498db; margin-bottom: 15px;">📋 项目信息</h3>
        
        <div style="margin-bottom: var(--spacing-xl);">
            <div style="display: flex; align-items: center; margin-bottom: var(--spacing-lg);">
                {% if project.status == 'completed' %}
                    <div class="status-indicator completed">
                        ✅
                    </div>
                {% elif project.status == 'in_progress' %}
                    <div class="status-indicator in_progress">
                        🔄
                    </div>
                {% elif project.status == 'draft' %}
                    <div class="status-indicator draft">
                        📝
                    </div>
                {% else %}
                    <div class="status-indicator error">
                        ❌
                    </div>
                {% endif %}
                
                <div>
                    {% if project.status == 'completed' %}
                        <h4 style="color: #2c3e50; margin-bottom: 5px;">项目已完成</h4>
                        <p style="color: #7f8c8d; margin: 0;">所有阶段已完成</p>
                    {% elif project.status == 'in_progress' %}
                        {% if todo_board %}
                            {% set current_stage = todo_board.stages | selectattr('status', 'equalto', 'running') | first %}
                            {% if current_stage %}
                                <h4 style="color: #2c3e50; margin-bottom: 5px;">{{ current_stage.name }}中</h4>
                                <p style="color: #7f8c8d; margin: 0;">当前正在执行</p>
                            {% else %}
                                {% set next_stage = todo_board.stages | selectattr('status', 'equalto', 'pending') | first %}
                                {% if next_stage %}
                                    <h4 style="color: #2c3e50; margin-bottom: 5px;">等待{{ next_stage.name }}</h4>
                                    <p style="color: #7f8c8d; margin: 0;">下一个阶段</p>
                                {% else %}
                                    <h4 style="color: #2c3e50; margin-bottom: 5px;">项目进行中</h4>
                                    <p style="color: #7f8c8d; margin: 0;">正在处理中</p>
                                {% endif %}
                            {% endif %}
                        {% else %}
                            <h4 style="color: #2c3e50; margin-bottom: 5px;">项目进行中</h4>
                            <p style="color: #7f8c8d; margin: 0;">正在处理中</p>
                        {% endif %}
                    {% elif project.status == 'draft' %}
                        <h4 style="color: #2c3e50; margin-bottom: 5px;">草稿状态</h4>
                        <p style="color: #7f8c8d; margin: 0;">等待开始</p>
                    {% else %}
                        <h4 style="color: #2c3e50; margin-bottom: 5px;">{{ project.status | title }}</h4>
                        <p style="color: #7f8c8d; margin: 0;">当前项目状态</p>
                    {% endif %}
                </div>
            </div>
        </div>
        
        <div class="project-info-grid">
            <div class="project-info-item">
                <strong>主题</strong>
                <p>{{ project.topic }}</p>
            </div>
            <div class="project-info-item">
                <strong>场景</strong>
                <p>{{ project.scenario }}</p>
            </div>
            <div class="project-info-item">
                <strong>版本</strong>
                <p>v{{ project.version }}</p>
            </div>
            <div class="project-info-item">
                <strong>创建时间</strong>
                <p>{{ project.created_at | strftime('%Y-%m-%d %H:%M') }}</p>
            </div>
        </div>

        {% if project.requirements %}
        <div style="background: var(--glass-bg); backdrop-filter: blur(15px); border: 1px solid var(--glass-border); padding: var(--spacing-xl); border-radius: var(--border-radius-lg); margin-bottom: var(--spacing-xl);">
            <strong style="color: var(--text-secondary); display: block; margin-bottom: var(--spacing-md); text-transform: uppercase; letter-spacing: 0.5px; font-size: 0.9rem;">特殊要求</strong>
            <p style="color: var(--text-primary); margin: 0; line-height: 1.6; font-size: 1.1rem;">{{ project.requirements }}</p>
        </div>
        {% endif %}
        
        <!-- Project Actions -->
        <div style="display: flex; gap: 10px; flex-wrap: wrap;">
            {% if project.status == 'in_progress' and todo_board %}
            <a href="/projects/{{ project.project_id }}/todo" class="btn btn-primary" style="flex: 1;">
                📋 TODO 看板
            </a>
            {% endif %}

            {% if project.status == 'completed' and project.slides_html %}
            <a href="/projects/{{ project.project_id }}/fullscreen" class="btn btn-success" target="_blank" style="flex: 1;">
                🔍 预览 PPT
            </a>
            {% endif %}
            
            <button onclick="archiveProject()" class="btn btn-warning" style="flex: 1;">
                📦 归档项目
            </button>
            
            <button onclick="deleteProject()" class="btn btn-danger" style="flex: 1;">
                🗑️ 删除项目
            </button>
        </div>
    </div>
    
    <!-- TODO Board Progress -->
    {% if todo_board %}
    <div class="card">
        <h3 style="color: #27ae60; margin-bottom: 15px;">📈 进度概览</h3>
        
        <div style="margin-bottom: 20px;">
            <div style="background: #ecf0f1; border-radius: 15px; overflow: hidden; height: 20px;">
                <div style="background: linear-gradient(90deg, #27ae60, #2ecc71); height: 100%; width: {{ todo_board.overall_progress }}%; transition: width 0.5s ease; border-radius: 15px;"></div>
            </div>
            <p style="text-align: center; margin-top: 10px; color: #2c3e50; font-weight: bold;">
                总体进度: {{ "%.1f" | format(todo_board.overall_progress) }}%
            </p>
        </div>
        
        <div style="background: #f8f9fa; padding: 15px; border-radius: 10px;">
            <h4 style="color: #2c3e50; margin-bottom: 10px;">阶段状态</h4>
            {% for stage in todo_board.stages %}
            <div style="display: flex; align-items: center; margin-bottom: 10px; padding: 12px; background: white; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                <div style="margin-right: 15px;">
                    {% if stage.status == 'completed' %}
                        <span style="color: #27ae60; font-size: 1.2em;">✅</span>
                    {% elif stage.status == 'running' %}
                        <span style="color: #3498db; font-size: 1.2em;">🔄</span>
                    {% elif stage.status == 'failed' %}
                        <span style="color: #e74c3c; font-size: 1.2em;">❌</span>
                    {% else %}
                        <span style="color: #95a5a6; font-size: 1.2em;">⏳</span>
                    {% endif %}
                </div>
                <div style="flex: 1;">
                    <strong style="color: #2c3e50; font-size: 0.9em;">{{ stage.name }}</strong>
                    <p style="color: #7f8c8d; font-size: 0.8em; margin: 2px 0 0 0;">{{ stage.description }}</p>
                    {% if stage.status == 'running' and stage.progress is defined %}
                    <div style="background: #ecf0f1; border-radius: 5px; overflow: hidden; height: 4px; margin-top: 5px;">
                        <div style="background: #3498db; height: 100%; width: {{ stage.progress }}%; transition: width 0.3s ease;"></div>
                    </div>
                    {% endif %}
                </div>
                <div style="margin-left: 15px;">
                    {% if stage.status == 'pending' %}
                        {% if stage.id == 'requirements_confirmation' %}
                            <a href="/projects/{{ project.project_id }}/todo" class="btn btn-primary" style="font-size: 0.8em; padding: 6px 12px;">
                                <i class="fas fa-play"></i> 开始
                            </a>
                        {% elif stage.id == 'outline_generation' %}
                            <a href="/projects/{{ project.project_id }}/todo" class="btn btn-primary" style="font-size: 0.8em; padding: 6px 12px;">
                                <i class="fas fa-brain"></i> 生成大纲
                            </a>
                        {% elif stage.id == 'ppt_creation' %}
                            <a href="/projects/{{ project.project_id }}/todo" class="btn btn-primary" style="font-size: 0.8em; padding: 6px 12px;">
                                <i class="fas fa-magic"></i> 生成PPT
                            </a>
                        {% else %}
                            <a href="/projects/{{ project.project_id }}/todo" class="btn btn-primary" style="font-size: 0.8em; padding: 6px 12px;">
                                <i class="fas fa-play"></i> 开始
                            </a>
                        {% endif %}
                    {% elif stage.status == 'running' %}
                        <a href="/projects/{{ project.project_id }}/todo" class="btn btn-info" style="font-size: 0.8em; padding: 6px 12px;">
                            <i class="fas fa-eye"></i> 查看进度
                        </a>
                    {% elif stage.status == 'completed' %}
                        <a href="/projects/{{ project.project_id }}/todo" class="btn btn-success" style="font-size: 0.8em; padding: 6px 12px;">
                            <i class="fas fa-check"></i> 已完成
                        </a>
                    {% elif stage.status == 'failed' %}
                        <a href="/projects/{{ project.project_id }}/todo" class="btn btn-warning" style="font-size: 0.8em; padding: 6px 12px;">
                            <i class="fas fa-redo"></i> 重试
                        </a>
                    {% endif %}
                </div>
            </div>
            {% endfor %}
        </div>
    </div>
    {% endif %}
</div>

<!-- PPT Outline Preview -->
{% if project.outline and project.outline is not none and project.outline.get('slides') %}
<div style="margin-top: 40px;">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h3 style="color: #2c3e50; margin: 0;">📄 PPT 大纲</h3>
        <div style="display: flex; gap: 10px;">
            <button onclick="toggleOutlineView()" class="btn btn-info" style="font-size: 0.9em;">
                <i class="fas fa-eye"></i> <span id="viewToggleText">详细视图</span>
            </button>
            <button onclick="editOutline()" class="btn btn-primary" style="font-size: 0.9em;">
                <i class="fas fa-edit"></i> 修改大纲
            </button>
            <button onclick="exportOutlineJSON()" class="btn btn-success" style="font-size: 0.9em;">
                <i class="fas fa-download"></i> 导出JSON
            </button>
        </div>
    </div>

    <div style="background: white; border-radius: 15px; padding: 30px; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);">
        <div style="text-align: center; margin-bottom: 20px;">
            <h4 style="color: #3498db; margin-bottom: 10px;">{{ project.outline.get('title', project.topic or '未命名大纲') }}</h4>
            <p style="color: #7f8c8d;">
                总共 {{ project.outline.get('slides', [])|length }} 页幻灯片 |
                场景: {{ project.outline.get('metadata', {}).get('scenario', project.scenario) }} |
                语言: {{ project.outline.get('metadata', {}).get('language', 'zh') }}
            </p>
        </div>

        <!-- 简洁视图 -->
        <div id="compactView" style="display: block;">
            <div style="background: #f8f9fa; border-radius: 10px; padding: 20px;">
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 15px;">
                    {% for slide in project.outline.get('slides', []) %}
                    <div style="padding: 15px; background: white; border-radius: 8px; border-left: 4px solid #3498db; transition: all 0.3s ease; box-shadow: 0 2px 4px rgba(0,0,0,0.1); position: relative;"
                         onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 8px rgba(0,0,0,0.15)'"
                         onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 4px rgba(0,0,0,0.1)'">

                        <!-- 操作按钮 -->
                        <div style="position: absolute; top: 10px; right: 10px; display: flex; gap: 5px;">
                            <button onclick="editSingleSlide({{ loop.index0 }})" class="btn btn-primary" style="font-size: 0.7em; padding: 4px 8px; border-radius: 4px;" title="编辑此页">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button onclick="viewSlideDetail({{ loop.index0 }})" class="btn btn-info" style="font-size: 0.7em; padding: 4px 8px; border-radius: 4px;" title="查看详情">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>

                        <div onclick="viewSlideDetail({{ loop.index0 }})" style="cursor: pointer; margin-right: 60px;">
                            <div style="display: flex; align-items: center; margin-bottom: 8px;">
                                <span style="background: #3498db; color: white; border-radius: 50%; width: 24px; height: 24px; display: flex; align-items: center; justify-content: center; font-size: 0.8em; font-weight: bold; margin-right: 10px;">
                                    {{ slide.get('page_number', loop.index) }}
                                </span>
                                <strong style="color: #2c3e50; font-size: 0.9em;">{{ slide.get('title', '未命名幻灯片') }}</strong>
                            </div>
                            {% if slide.get('subtitle') %}
                            <p style="color: #7f8c8d; font-size: 0.8em; margin: 5px 0; font-style: italic;">{{ slide.get('subtitle') }}</p>
                            {% endif %}
                            <div style="color: #666; font-size: 0.8em; line-height: 1.4;">
                                {% if slide.get('content_points') and slide.get('content_points')|length > 0 %}
                                    {{ slide.get('content_points')[0][:80] }}{% if slide.get('content_points')[0]|length > 80 %}...{% endif %}
                                    {% if slide.get('content_points')|length > 1 %}
                                    <br><span style="color: #95a5a6;">+{{ slide.get('content_points')|length - 1 }} 个要点</span>
                                    {% endif %}
                                {% elif slide.get('content') %}
                                    {{ slide.get('content')[:80] }}{% if slide.get('content')|length > 80 %}...{% endif %}
                                {% else %}
                                    <span style="color: #95a5a6;">暂无内容</span>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>

        <!-- 详细视图 -->
        <div id="detailView" style="display: none; max-height: 500px; overflow-y: auto;">
            {% for slide in project.outline.get('slides', []) %}
            <div style="padding: 20px; margin-bottom: 15px; background: #f8f9fa; border-radius: 10px; border-left: 4px solid #3498db; position: relative;">
                <div style="display: flex; align-items: center; margin-bottom: 15px;">
                    <span style="background: #3498db; color: white; border-radius: 50%; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; font-weight: bold; margin-right: 15px;">
                        {{ slide.get('page_number', loop.index) }}
                    </span>
                    <div style="flex: 1;">
                        <strong style="color: #2c3e50; font-size: 1.1em;">{{ slide.get('title', '未命名幻灯片') }}</strong>
                        {% if slide.get('subtitle') %}
                        <br><em style="color: #7f8c8d; font-size: 0.9em;">{{ slide.get('subtitle') }}</em>
                        {% endif %}
                    </div>
                    <button onclick="editSingleSlide({{ loop.index0 }})" class="btn btn-primary" style="font-size: 0.8em; padding: 6px 12px;" title="编辑此页">
                        <i class="fas fa-edit"></i> 编辑
                    </button>
                </div>

                {% if slide.get('content_points') %}
                <div style="margin-top: 10px;">
                    <h5 style="color: #555; margin-bottom: 8px; font-size: 0.9em;">内容要点：</h5>
                    <ul style="margin: 0; padding-left: 20px; color: #555; line-height: 1.6;">
                        {% for point in slide.get('content_points', []) %}
                        <li style="margin-bottom: 5px;">{{ point }}</li>
                        {% endfor %}
                    </ul>
                </div>
                {% elif slide.get('content') %}
                <div style="margin-top: 10px;">
                    <h5 style="color: #555; margin-bottom: 8px; font-size: 0.9em;">内容：</h5>
                    <div style="background: white; padding: 15px; border-radius: 6px; color: #555; line-height: 1.6; white-space: pre-wrap;">{{ slide.get('content') }}</div>
                </div>
                {% endif %}

                {% if slide.get('slide_type') %}
                <div style="margin-top: 10px;">
                    <span style="background: #e8f4fd; color: #3498db; padding: 4px 8px; border-radius: 4px; font-size: 0.8em;">
                        类型: {{ slide.get('slide_type') }}
                    </span>
                </div>
                {% endif %}
            </div>
            {% endfor %}
        </div>
    </div>
</div>
{% elif project.outline and project.outline is not none %}
<!-- Show outline content if it exists but doesn't have slides structure -->
<div style="margin-top: 40px;">
    <h3 style="color: #2c3e50; margin-bottom: 20px; text-align: center;">📄 PPT 大纲</h3>

    <div style="background: white; border-radius: 15px; padding: 30px; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);">
        <div style="text-align: center; margin-bottom: 20px;">
            <h4 style="color: #3498db; margin-bottom: 10px;">{{ project.outline.get('title', project.topic or '未命名大纲') if project.outline else (project.topic or '未命名大纲') }}</h4>
            <p style="color: #7f8c8d;">大纲内容</p>
        </div>

        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; max-height: 400px; overflow-y: auto;">
            {% if project.outline and project.outline.get('content') %}
            <pre style="white-space: pre-wrap; font-family: 'Courier New', monospace; font-size: 12px; line-height: 1.4; margin: 0;">{{ project.outline.get('content') }}</pre>
            {% else %}
            <p style="color: #7f8c8d; text-align: center; margin: 0;">大纲内容正在生成中...</p>
            {% endif %}
        </div>
    </div>
</div>
{% endif %}

<!-- Version History -->
{% if versions %}
<div style="margin-top: 40px;">
    <h3 style="color: #2c3e50; margin-bottom: 20px; text-align: center;">📚 版本历史</h3>
    
    <div style="background: white; border-radius: 15px; padding: 30px; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);">
        {% for version in versions %}
        <div style="display: flex; align-items: center; padding: 15px; margin-bottom: 10px; background: #f8f9fa; border-radius: 8px;">
            <div style="margin-right: 20px;">
                <div style="width: 40px; height: 40px; background: #3498db; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold;">
                    v{{ version.version }}
                </div>
            </div>
            
            <div style="flex: 1;">
                <strong style="color: #2c3e50;">{{ version.description }}</strong>
                <p style="color: #7f8c8d; margin: 5px 0 0 0; font-size: 0.9em;">
                    {{ version.timestamp | strftime('%Y-%m-%d %H:%M:%S') }}
                </p>
            </div>
            
            <div style="margin-left: 15px;">
                <button onclick="restoreVersion({{ version.version }})" class="btn btn-primary" style="font-size: 0.9em;">
                    🔄 恢复此版本
                </button>
            </div>
        </div>
        {% endfor %}
    </div>
</div>
{% endif %}

<!-- Navigation -->
<div style="text-align: center; margin-top: 40px;">
    <a href="/projects" class="btn" style="background: #95a5a6; margin: 0 10px;">
        📋 返回项目列表
    </a>
    <a href="/dashboard" class="btn btn-primary" style="margin: 0 10px;">
        📊 项目仪表板
    </a>
</div>
{% endblock %}

{% block extra_js %}
<script>
const projectId = '{{ project.project_id }}';
const projectOutline = {{ project.outline | tojson if project.outline else 'null' }};
const projectSlides = {{ project.outline.get('slides', []) | tojson if project.outline else '[]' }};

async function archiveProject() {
    if (confirm('确定要归档这个项目吗？归档后项目将不会显示在活跃项目列表中。')) {
        try {
            const response = await fetch(`/api/projects/${projectId}/archive`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            });
            
            if (response.ok) {
                alert('项目已归档');
                window.location.href = '/projects';
            } else {
                alert('归档失败，请重试');
            }
        } catch (error) {
            console.error('Error archiving project:', error);
            alert('归档失败: ' + error.message);
        }
    }
}

async function deleteProject() {
    if (confirm('确定要删除这个项目吗？此操作不可撤销！')) {
        if (confirm('请再次确认删除操作，所有数据将永久丢失！')) {
            try {
                // Show loading indicator
                const deleteBtn = document.querySelector('button[onclick="deleteProject()"]');
                const originalText = deleteBtn.innerHTML;
                deleteBtn.innerHTML = '🔄 删除中...';
                deleteBtn.disabled = true;

                const response = await fetch(`/api/database/projects/${projectId}`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });

                const result = await response.json();

                if (response.ok) {
                    alert('项目删除成功！');
                    window.location.href = '/projects';
                } else {
                    throw new Error(result.detail || '删除失败');
                }
            } catch (error) {
                console.error('Error deleting project:', error);
                alert('删除失败: ' + error.message);

                // Restore button state
                const deleteBtn = document.querySelector('button[onclick="deleteProject()"]');
                deleteBtn.innerHTML = '🗑️ 删除项目';
                deleteBtn.disabled = false;
            }
        }
    }
}

// 大纲视图切换
let isDetailView = false;

function toggleOutlineView() {
    const compactView = document.getElementById('compactView');
    const detailView = document.getElementById('detailView');
    const toggleText = document.getElementById('viewToggleText');

    if (isDetailView) {
        compactView.style.display = 'block';
        detailView.style.display = 'none';
        toggleText.textContent = '详细视图';
        isDetailView = false;
    } else {
        compactView.style.display = 'none';
        detailView.style.display = 'block';
        toggleText.textContent = '简洁视图';
        isDetailView = true;
    }
}

// 查看幻灯片详情
function viewSlideDetail(slideIndex) {
    const slide = projectSlides[slideIndex];

    if (!slide) return;

    // 创建模态框显示详细信息
    const modal = document.createElement('div');
    modal.style.cssText = `
        position: fixed; top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(0,0,0,0.5); z-index: 1000; display: flex;
        align-items: center; justify-content: center; padding: 20px;
    `;

    const content = document.createElement('div');
    content.style.cssText = `
        background: white; border-radius: 15px; padding: 30px;
        max-width: 600px; max-height: 80vh; overflow-y: auto;
        box-shadow: 0 10px 30px rgba(0,0,0,0.3);
    `;

    let contentPoints = '';
    if (slide.content_points && slide.content_points.length > 0) {
        contentPoints = '<h5 style="color: #555; margin: 15px 0 8px 0;">内容要点：</h5><ul style="margin: 0; padding-left: 20px; color: #555; line-height: 1.6;">';
        slide.content_points.forEach(point => {
            contentPoints += `<li style="margin-bottom: 5px;">${point}</li>`;
        });
        contentPoints += '</ul>';
    } else if (slide.content) {
        contentPoints = `<h5 style="color: #555; margin: 15px 0 8px 0;">内容：</h5><div style="background: #f8f9fa; padding: 15px; border-radius: 6px; color: #555; line-height: 1.6; white-space: pre-wrap;">${slide.content}</div>`;
    }

    content.innerHTML = `
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3 style="color: #2c3e50; margin: 0;">第${slide.page_number || slideIndex + 1}页详情</h3>
            <button onclick="this.closest('.modal').remove()" style="background: #e74c3c; color: white; border: none; border-radius: 50%; width: 30px; height: 30px; cursor: pointer; font-size: 16px;">×</button>
        </div>
        <h4 style="color: #3498db; margin-bottom: 10px;">${slide.title || '未命名幻灯片'}</h4>
        ${slide.subtitle ? `<p style="color: #7f8c8d; font-style: italic; margin-bottom: 15px;">${slide.subtitle}</p>` : ''}
        ${contentPoints}
        ${slide.slide_type ? `<div style="margin-top: 15px;"><span style="background: #e8f4fd; color: #3498db; padding: 6px 12px; border-radius: 6px; font-size: 0.9em;">类型: ${slide.slide_type}</span></div>` : ''}
    `;

    modal.className = 'modal';
    modal.appendChild(content);
    document.body.appendChild(modal);

    // 点击背景关闭
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            modal.remove();
        }
    });
}

// 编辑大纲
function editOutline() {
    if (!projectOutline) {
        alert('大纲数据不存在，无法编辑');
        return;
    }

    // 创建编辑模态框
    const modal = document.createElement('div');
    modal.style.cssText = `
        position: fixed; top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(0,0,0,0.5); z-index: 1000; display: flex;
        align-items: center; justify-content: center; padding: 20px;
    `;

    const content = document.createElement('div');
    content.style.cssText = `
        background: white; border-radius: 15px; padding: 30px;
        width: 90%; max-width: 800px; height: 80vh; display: flex;
        flex-direction: column; box-shadow: 0 10px 30px rgba(0,0,0,0.3);
    `;

    content.innerHTML = `
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3 style="color: #2c3e50; margin: 0;">编辑PPT大纲</h3>
            <button onclick="this.closest('.modal').remove()" style="background: #e74c3c; color: white; border: none; border-radius: 50%; width: 30px; height: 30px; cursor: pointer; font-size: 16px;">×</button>
        </div>
        <div style="flex: 1; display: flex; flex-direction: column;">
            <textarea id="outlineEditor" style="flex: 1; border: 2px solid #ecf0f1; border-radius: 8px; padding: 15px; font-family: 'Courier New', monospace; font-size: 14px; line-height: 1.5; resize: none;" placeholder="编辑大纲JSON...">${JSON.stringify(projectOutline, null, 2)}</textarea>
            <div style="display: flex; gap: 10px; margin-top: 15px; justify-content: flex-end;">
                <button onclick="this.closest('.modal').remove()" class="btn" style="background: #95a5a6;">取消</button>
                <button onclick="saveOutlineChanges()" class="btn btn-primary">保存修改</button>
            </div>
        </div>
    `;

    modal.className = 'modal';
    modal.appendChild(content);
    document.body.appendChild(modal);
}

// 保存大纲修改
async function saveOutlineChanges() {
    const editor = document.getElementById('outlineEditor');
    try {
        const newOutline = JSON.parse(editor.value);

        const response = await fetch(`/projects/${projectId}/update-outline`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ outline_content: JSON.stringify(newOutline, null, 2) })
        });

        if (response.ok) {
            alert('大纲修改成功！');
            window.location.reload();
        } else {
            const error = await response.json();
            alert('保存失败: ' + (error.detail || '未知错误'));
        }
    } catch (error) {
        if (error instanceof SyntaxError) {
            alert('JSON格式错误，请检查语法！');
        } else {
            console.error('Error saving outline:', error);
            alert('保存失败: ' + error.message);
        }
    }
}

// 导出大纲为JSON文件
function exportOutlineJSON() {
    if (!projectOutline) {
        alert('大纲数据不存在，无法导出');
        return;
    }

    const dataStr = JSON.stringify(projectOutline, null, 2);
    const dataBlob = new Blob([dataStr], {type: 'application/json'});

    const link = document.createElement('a');
    link.href = URL.createObjectURL(dataBlob);
    link.download = `${(projectOutline.title || 'ppt_outline')}_${new Date().toISOString().split('T')[0]}.json`;

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 显示成功提示
    const toast = document.createElement('div');
    toast.style.cssText = `
        position: fixed; top: 20px; right: 20px; background: #27ae60;
        color: white; padding: 15px 20px; border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15); z-index: 1001;
        font-size: 14px; font-weight: bold;
    `;
    toast.textContent = '✅ 大纲JSON文件已导出';
    document.body.appendChild(toast);

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

// 编辑单页幻灯片
function editSingleSlide(slideIndex) {
    if (!projectSlides || !projectSlides[slideIndex]) {
        alert('幻灯片不存在');
        return;
    }

    const slide = projectSlides[slideIndex];

    // 创建编辑模态框
    const modal = document.createElement('div');
    modal.style.cssText = `
        position: fixed; top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(0,0,0,0.5); z-index: 1000; display: flex;
        align-items: center; justify-content: center; padding: 20px;
    `;

    const content = document.createElement('div');
    content.style.cssText = `
        background: white; border-radius: 15px; padding: 30px;
        width: 90%; max-width: 700px; max-height: 85vh; overflow-y: auto;
        box-shadow: 0 10px 30px rgba(0,0,0,0.3);
    `;

    // 构建内容要点的编辑界面
    let contentPointsHtml = '<h5 style="color: #555; margin: 15px 0 8px 0;">内容要点：</h5>';
    contentPointsHtml += '<div id="contentPointsContainer">';

    if (slide.content_points && slide.content_points.length > 0) {
        slide.content_points.forEach((point, index) => {
            contentPointsHtml += `
                <div style="display: flex; align-items: center; margin-bottom: 8px;">
                    <input type="text" id="point_${index}" value="${point.replace(/"/g, '&quot;')}"
                           style="flex: 1; padding: 8px; border: 1px solid #ddd; border-radius: 4px; margin-right: 8px;">
                    <button onclick="removeContentPoint(${index})" style="background: #e74c3c; color: white; border: none; border-radius: 4px; padding: 6px 10px; cursor: pointer;">删除</button>
                </div>
            `;
        });
    }

    contentPointsHtml += '</div>';
    contentPointsHtml += `
        <button onclick="addContentPoint()" style="background: #27ae60; color: white; border: none; border-radius: 4px; padding: 8px 15px; cursor: pointer; margin-top: 10px;">
            + 添加要点
        </button>
    `;

    content.innerHTML = `
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3 style="color: #2c3e50; margin: 0;">编辑第${slide.page_number || slideIndex + 1}页</h3>
            <button onclick="this.closest('.modal').remove()" style="background: #e74c3c; color: white; border: none; border-radius: 50%; width: 30px; height: 30px; cursor: pointer; font-size: 16px;">×</button>
        </div>

        <div style="margin-bottom: 15px;">
            <label style="display: block; margin-bottom: 5px; color: #555; font-weight: bold;">标题：</label>
            <input type="text" id="slideTitle" value="${slide.title || ''}"
                   style="width: 100%; padding: 10px; border: 2px solid #ecf0f1; border-radius: 6px; font-size: 14px;">
        </div>

        <div style="margin-bottom: 15px;">
            <label style="display: block; margin-bottom: 5px; color: #555; font-weight: bold;">副标题：</label>
            <input type="text" id="slideSubtitle" value="${slide.subtitle || ''}"
                   style="width: 100%; padding: 10px; border: 2px solid #ecf0f1; border-radius: 6px; font-size: 14px;">
        </div>

        <div style="margin-bottom: 15px;">
            <label style="display: block; margin-bottom: 5px; color: #555; font-weight: bold;">幻灯片类型：</label>
            <select id="slideType" style="width: 100%; padding: 10px; border: 2px solid #ecf0f1; border-radius: 6px; font-size: 14px;">
                <option value="content" ${slide.slide_type === 'content' ? 'selected' : ''}>内容页</option>
                <option value="title" ${slide.slide_type === 'title' ? 'selected' : ''}>标题页</option>
                <option value="conclusion" ${slide.slide_type === 'conclusion' ? 'selected' : ''}>结论页</option>
            </select>
        </div>

        <div id="contentPointsSection" style="margin-bottom: 20px;">
            ${contentPointsHtml}
        </div>

        ${slide.content ? `
        <div style="margin-bottom: 15px;">
            <label style="display: block; margin-bottom: 5px; color: #555; font-weight: bold;">内容：</label>
            <textarea id="slideContent" rows="4"
                      style="width: 100%; padding: 10px; border: 2px solid #ecf0f1; border-radius: 6px; font-size: 14px; resize: vertical;">${slide.content}</textarea>
        </div>
        ` : ''}

        <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
            <button onclick="this.closest('.modal').remove()" class="btn" style="background: #95a5a6;">取消</button>
            <button onclick="saveSingleSlideChanges(${slideIndex})" class="btn btn-primary">保存修改</button>
        </div>
    `;

    modal.className = 'modal';
    modal.appendChild(content);
    document.body.appendChild(modal);

    // 存储当前编辑的幻灯片索引
    window.currentEditingSlideIndex = slideIndex;
}

// 添加内容要点
function addContentPoint() {
    // 查找内容要点容器
    const container = document.getElementById('contentPointsContainer');

    if (!container) {
        console.error('找不到内容要点容器');
        alert('无法找到内容要点容器，请刷新页面重试');
        return;
    }

    // 计算当前要点数量
    const existingPoints = document.querySelectorAll('input[id^="point_"]');
    const pointIndex = existingPoints.length;

    const pointDiv = document.createElement('div');
    pointDiv.style.cssText = 'display: flex; align-items: center; margin-bottom: 8px;';
    pointDiv.innerHTML = `
        <input type="text" id="point_${pointIndex}" placeholder="输入要点内容..."
               style="flex: 1; padding: 8px; border: 1px solid #ddd; border-radius: 4px; margin-right: 8px;">
        <button onclick="removeContentPoint(${pointIndex})" style="background: #e74c3c; color: white; border: none; border-radius: 4px; padding: 6px 10px; cursor: pointer;">删除</button>
    `;

    // 直接添加到容器末尾
    container.appendChild(pointDiv);
}

// 删除内容要点
function removeContentPoint(index) {
    const pointElement = document.getElementById(`point_${index}`);
    if (pointElement) {
        pointElement.closest('div').remove();
    }
}

// 保存单页幻灯片修改
async function saveSingleSlideChanges(slideIndex) {
    try {
        const title = document.getElementById('slideTitle').value.trim();
        const subtitle = document.getElementById('slideSubtitle').value.trim();
        const slideType = document.getElementById('slideType').value;
        const content = document.getElementById('slideContent')?.value.trim() || '';

        // 收集所有内容要点
        const contentPoints = [];
        const pointInputs = document.querySelectorAll('input[id^="point_"]');
        pointInputs.forEach(input => {
            const value = input.value.trim();
            if (value) {
                contentPoints.push(value);
            }
        });

        if (!title) {
            alert('请输入幻灯片标题');
            return;
        }

        // 构建更新的幻灯片数据
        const updatedSlide = {
            ...projectSlides[slideIndex],
            title: title,
            subtitle: subtitle || undefined,
            slide_type: slideType,
            content_points: contentPoints.length > 0 ? contentPoints : undefined,
            content: content || undefined
        };

        // 更新本地数据
        projectSlides[slideIndex] = updatedSlide;

        // 更新大纲中的幻灯片
        if (!projectOutline) {
            alert('大纲数据不存在，无法保存修改');
            return;
        }
        const updatedOutline = { ...projectOutline };
        updatedOutline.slides[slideIndex] = updatedSlide;

        // 发送到服务器
        const response = await fetch(`/projects/${projectId}/update-outline`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ outline_content: JSON.stringify(updatedOutline, null, 2) })
        });

        if (response.ok) {
            // 关闭模态框
            document.querySelector('.modal').remove();

            // 显示成功提示
            const toast = document.createElement('div');
            toast.style.cssText = `
                position: fixed; top: 20px; right: 20px; background: #27ae60;
                color: white; padding: 15px 20px; border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15); z-index: 1001;
                font-size: 14px; font-weight: bold;
            `;
            toast.textContent = `✅ 第${slideIndex + 1}页修改成功`;
            document.body.appendChild(toast);

            setTimeout(() => {
                toast.remove();
                // 刷新页面以显示更新
                window.location.reload();
            }, 2000);
        } else {
            const error = await response.json();
            alert('保存失败: ' + (error.detail || '未知错误'));
        }
    } catch (error) {
        console.error('Error saving slide changes:', error);
        alert('保存失败: ' + error.message);
    }
}

async function restoreVersion(version) {
    if (confirm(`确定要恢复到版本 v${version} 吗？当前未保存的更改将丢失。`)) {
        try {
            const response = await fetch(`/api/projects/${projectId}/versions/${version}/restore`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            });
            
            if (response.ok) {
                alert('版本恢复成功');
                window.location.reload();
            } else {
                alert('版本恢复失败，请重试');
            }
        } catch (error) {
            console.error('Error restoring version:', error);
            alert('版本恢复失败: ' + error.message);
        }
    }
}

</script>
{% endblock %}
