<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🎯 MCP反馈收集工具</title>
    <meta name="description" content="基于WebSocket的MCP反馈收集工具">
    
    <!-- 安全策略 - WebSocket支持 -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.socket.io; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self' ws: wss:;">
    
    <!-- Favicon -->
    <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🎯</text></svg>">
    
    <!-- Socket.IO客户端 -->
    <script src="https://cdn.socket.io/4.7.5/socket.io.min.js" crossorigin="anonymous"></script>
    
    <!-- CSS样式 -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/websocket-status.css') }}">
</head>
<body>
    <div class="container">
        <!-- 工作汇报区域 -->
        <div class="section work-report-section">
            <div class="section-header">
                📋 AI工作汇报
                <div class="timeout-info">
                    <span class="timeout-message">剩余时间: <span id="timeoutCountdown"></span></span>
                </div>
            </div>
            <div class="section-content">
                <div class="work-summary" id="workSummary">
                    {{ work_summary or "等待工作汇报..." }}
                </div>
            </div>
        </div>
        
        <!-- 反馈表单 -->
        <form id="feedbackForm">
            <div class="section feedback-section">
                <div class="section-header">
                    💬 您的反馈
                </div>
                <div class="section-content">
                    <!-- 建议选项 -->
                    {% if suggest %}
                    <div class="suggest-options">
                        <div class="suggest-header">💡 建议选项：</div>
                        <div class="suggest-list">
                            {% for option in suggest %}
                            <button type="button" class="suggest-btn" data-value="{{ option }}">
                                {{ option }}
                            </button>
                            {% endfor %}
                        </div>
                    </div>
                    {% endif %}
                    
                    <!-- 反馈输入 -->
                    <div class="form-group">
                        <textarea 
                            id="textFeedback" 
                            name="textFeedback" 
                            placeholder="请输入您的反馈内容...&#10;提示：可粘贴图片 (Ctrl+V)"
                            rows="4"
                        ></textarea>
                    </div>
                    
                    <!-- 图片预览 -->
                    <div id="imagePreview" class="image-preview"></div>
                    
                    <!-- 连接状态和消息区域 -->
                    <div class="connection-status-container">
                        <div id="connection-status" class="connection-status connecting">连接中...</div>
                        <div id="message-area" class="message-area"></div>
                    </div>
                    
                    <!-- 操作按钮 -->
                    <div class="button-group">
                        <button type="button" id="uploadBtn" class="btn btn-secondary">
                            🖼️ 选择图片
                        </button>
                        <button type="button" onclick="window.close()" class="btn btn-secondary">
                            ❌ 取消
                        </button>
                        <button type="submit" id="submitBtn" class="btn btn-primary">
                            ✅ 提交反馈
                        </button>
                    </div>
                    
                    <!-- 隐藏的文件输入 -->
                    <input type="file" id="fileInput" accept="image/*" multiple style="display: none;">
                </div>
            </div>
        </form>
    </div>

    <!-- 应用数据 -->
    <script type="application/json" id="appConfig">
    {
        "timeout_seconds": {{ timeout_seconds }},
        "suggest": {{ suggest_json | safe }},
        "csrf_token": "{{ csrf_token }}"
    }
    </script>

    <!-- 模块化JavaScript -->
    <script type="module">
        import { WebSocketManager } from '{{ url_for("static", filename="js/modules/websocket-manager.js") }}';
        import { UIStatusManager } from '{{ url_for("static", filename="js/modules/ui-status-manager.js") }}';
        
        // 应用配置
        const appConfig = JSON.parse(document.getElementById('appConfig').textContent);
        
        // 初始化管理器
        const wsManager = new WebSocketManager({
            heartbeatInterval: 30000,
            maxReconnectAttempts: 5
        });
        
        const uiManager = new UIStatusManager();
        
        // WebSocket事件处理
        wsManager.on('connected', () => {
            uiManager.updateConnectionStatus('connected', '已连接');
            uiManager.showSuccess('WebSocket连接已建立');
        });
        
        wsManager.on('ready', (data) => {
            uiManager.updateSubmitButton('ready');
            uiManager.showInfo(`客户端ID: ${data.client_id}`);
        });
        
        wsManager.on('disconnected', (reason) => {
            uiManager.updateConnectionStatus('disconnected', '连接断开');
            uiManager.updateSubmitButton('offline');
            uiManager.showWarning(`连接断开: ${reason}`);
        });
        
        wsManager.on('error', (error) => {
            uiManager.updateConnectionStatus('error', '连接错误');
            uiManager.showError('连接出现问题，请刷新页面重试');
        });
        
        wsManager.on('feedback_received', (data) => {
            uiManager.updateSubmitButton('success');
            uiManager.showSuccess('反馈提交成功！');
            setTimeout(() => window.close(), 2000);
        });
        
        // 表单提交处理
        const form = document.getElementById('feedbackForm');
        const textArea = document.getElementById('textFeedback');
        const fileInput = document.getElementById('fileInput');
        const uploadBtn = document.getElementById('uploadBtn');
        const imagePreview = document.getElementById('imagePreview');
        
        let selectedImages = [];
        
        // 文件上传按钮
        uploadBtn.addEventListener('click', () => fileInput.click());
        
        // 文件选择处理
        fileInput.addEventListener('change', handleFileSelect);
        
        // 图片粘贴处理
        textArea.addEventListener('paste', handlePaste);
        
        // 拖拽处理
        textArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            textArea.classList.add('dragover');
        });
        
        textArea.addEventListener('dragleave', () => {
            textArea.classList.remove('dragover');
        });
        
        textArea.addEventListener('drop', (e) => {
            e.preventDefault();
            textArea.classList.remove('dragover');
            handleFiles(e.dataTransfer.files);
        });
        
        // 建议选项处理
        document.querySelectorAll('.suggest-btn').forEach(btn => {
            btn.addEventListener('click', async () => {
                const value = btn.dataset.value;
                if (wsManager.canSubmitFeedback()) {
                    uiManager.updateSubmitButton('submitting');
                    try {
                        await wsManager.submitFeedback({ text: value, images: [] });
                    } catch (error) {
                        uiManager.updateSubmitButton('error');
                        uiManager.showError('提交失败，请重试');
                    }
                } else {
                    textArea.value = value;
                    textArea.focus();
                }
            });
        });
        
        // 表单提交
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            if (!wsManager.canSubmitFeedback()) {
                uiManager.showError('WebSocket连接未就绪，请稍候重试');
                return;
            }
            
            const text = textArea.value.trim();
            
            if (!text && selectedImages.length === 0) {
                uiManager.showWarning('请输入反馈内容或选择图片');
                return;
            }
            
            uiManager.updateSubmitButton('submitting');
            
            try {
                await wsManager.submitFeedback({
                    text: text,
                    images: selectedImages
                });
            } catch (error) {
                uiManager.updateSubmitButton('error');
                uiManager.showError('提交失败，请重试');
                console.error('提交错误:', error);
            }
        });
        
        // 文件处理函数
        function handleFileSelect(e) {
            handleFiles(e.target.files);
        }
        
        function handlePaste(e) {
            const items = e.clipboardData.items;
            for (let item of items) {
                if (item.type.startsWith('image/')) {
                    e.preventDefault();
                    const file = item.getAsFile();
                    addImageFile(file);
                }
            }
        }
        
        function handleFiles(files) {
            for (let file of files) {
                if (file.type.startsWith('image/')) {
                    addImageFile(file);
                }
            }
        }
        
        function addImageFile(file) {
            if (selectedImages.length >= 5) {
                uiManager.showWarning('最多只能选择5张图片');
                return;
            }
            
            const reader = new FileReader();
            reader.onload = (e) => {
                const imageData = e.target.result;
                selectedImages.push(imageData);
                updateImagePreview();
                uiManager.showInfo(`已添加图片 (${selectedImages.length}/5)`);
            };
            reader.readAsDataURL(file);
        }
        
        function updateImagePreview() {
            imagePreview.innerHTML = selectedImages.map((src, index) => `
                <div class="preview-item">
                    <img src="${src}" class="preview-image" alt="预览图片 ${index + 1}">
                    <button type="button" class="remove-btn" onclick="removeImage(${index})">×</button>
                </div>
            `).join('');
        }
        
        // 全局删除图片函数
        window.removeImage = function(index) {
            selectedImages.splice(index, 1);
            updateImagePreview();
            uiManager.showInfo(`已删除图片 (${selectedImages.length}/5)`);
        };
        
        // 超时倒计时
        let timeoutSeconds = appConfig.timeout_seconds;
        const countdownElement = document.getElementById('timeoutCountdown');
        
        function updateCountdown() {
            if (timeoutSeconds > 0) {
                const minutes = Math.floor(timeoutSeconds / 60);
                const seconds = timeoutSeconds % 60;
                countdownElement.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;
                timeoutSeconds--;
                setTimeout(updateCountdown, 1000);
            } else {
                countdownElement.textContent = '已超时';
                window.close();
            }
        }
        
        updateCountdown();
        
        // 页面加载完成提示
        uiManager.showInfo('页面加载完成，正在建立WebSocket连接...');
    </script>
</body>
</html> 