
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ filename }} - 代码编辑器</title>
    <link rel="stylesheet" href="/static/lib/codemirror/codemirror.min.css">
    <script src="/static/lib/codemirror/codemirror.min.js"></script>
    <script src="/static/lib/codemirror/mode/python/python.min.js"></script>
    <script src="/static/lib/codemirror/mode/javascript/javascript.min.js"></script>
    <script src="/static/lib/codemirror/mode/htmlmixed/htmlmixed.min.js"></script>
    <script src="/static/lib/codemirror/mode/css/css.min.js"></script>
    <script src="/static/lib/codemirror/mode/xml/xml.min.js"></script>
    <script src="/static/lib/codemirror/mode/clike/clike.min.js"></script>
    <script src="/static/lib/codemirror/mode/markdown/markdown.min.js"></script>
    <script src="/static/lib/codemirror/addon/edit/matchbrackets.min.js"></script>
    <script src="/static/lib/codemirror/addon/comment/comment.min.js"></script>
    <script src="/static/lib/codemirror/keymap/sublime.min.js"></script>
    <script src="/static/lib/codemirror/addon/selection/active-line.min.js"></script>
    <script src="/static/lib/codemirror/addon/search/searchcursor.min.js"></script>
    <script src="/static/lib/codemirror/addon/dialog/dialog.min.js"></script>
    <script src="/static/lib/codemirror/addon/search/search.min.js"></script>
    <script src="/static/lib/codemirror/addon/edit/closebrackets.min.js"></script>
    <script src="/static/lib/codemirror/addon/fold/foldcode.min.js"></script>
    <script src="/static/lib/codemirror/addon/fold/foldgutter.min.js"></script>
    <script src="/static/lib/codemirror/addon/fold/brace-fold.min.js"></script>
    <link rel="stylesheet" href="/static/lib/codemirror/addon/dialog/dialog.min.css">
    <link rel="stylesheet" href="/static/lib/codemirror/addon/fold/foldgutter.min.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8f9fa;
        }
        .editor-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 0;
            position: sticky;
            top: 0;
            z-index: 100;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 0.25rem;
            height: 40px;
        }
        .header-buttons {
            display: none;
        }
        .editor-title-wrap {
            flex-grow: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            min-width: 0;
        }
        .editor-title {
            margin: 0;
            font-size: 0.9rem;
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .editor-btn {
            padding: 2px 6px;
            background-color: rgba(255,255,255,0.2);
            color: white;
            text-decoration: none;
            border-radius: 4px;
            border: none;
            cursor: pointer;
            font-size: 12px;
            line-height: 1;
            height: 28px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
        .editor-btn:hover {
            background-color: rgba(255,255,255,0.3);
        }
        .editor-btn[disabled] {
            opacity: 0.55;
            cursor: not-allowed;
        }
        .editor-btn.copied {
            background-color: rgba(72, 187, 120, 0.45);
        }
        .editor-btn.copy-failed {
            background-color: rgba(245, 101, 101, 0.45);
        }
        .editor-container {
            padding: 0;
            height: calc(100vh - 40px);
            position: relative;
        }
        .floating-buttons {
            position: absolute;
            right: 10px;
            top: 10px;
            z-index: 100;
            display: flex;
            gap: 0.25rem;
            background: rgba(0, 0, 0, 0.5);
            padding: 6px;
            border-radius: 8px;
        }
        .CodeMirror {
            height: 100% !important;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 7px;
            line-height: 1.5;
            border: 0;
            border-radius: 0;
        }
        .CodeMirror-vscrollbar {
            right: 0 !important;
            width: 6px !important;
        }
        .CodeMirror-hscrollbar {
            bottom: 0 !important;
            height: 6px !important;
        }
        .CodeMirror-vscrollbar, .CodeMirror-hscrollbar {
            scrollbar-width: thin;
            scrollbar-color: rgba(0,0,0,0.35) transparent;
        }
        .CodeMirror-vscrollbar::-webkit-scrollbar { width: 6px; }
        .CodeMirror-hscrollbar::-webkit-scrollbar { height: 6px; }
        .CodeMirror-vscrollbar::-webkit-scrollbar-track,
        .CodeMirror-hscrollbar::-webkit-scrollbar-track { background: transparent; }
        .CodeMirror-vscrollbar::-webkit-scrollbar-thumb,
        .CodeMirror-hscrollbar::-webkit-scrollbar-thumb {
            background: rgba(0,0,0,0.35);
            border-radius: 999px;
        }
        .save-status {
            margin-top: 0.5rem;
            padding: 0.5rem;
            border-radius: 5px;
            text-align: center;
            font-size: 0.9rem;
            display: none;
        }
        .save-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .save-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .ai-panel {
            position: fixed; inset: 0; z-index: 1000;
            display: flex; align-items: center; justify-content: center;
        }
        .ai-panel-backdrop {
            position: absolute; inset: 0; background: rgba(0,0,0,0.6);
        }
        .ai-panel-content {
            position: relative; width: 80%; max-width: 600px;
            background: #1a1a2e; border-radius: 12px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.5);
            overflow: hidden;
        }
        .ai-panel-header {
            padding: 14px 16px; background: linear-gradient(135deg, #667eea, #764ba2);
            display: flex; align-items: center; justify-content: space-between;
        }
        .ai-panel-header span { color: #fff; font-weight: 500; }
        .ai-panel-close {
            width: 28px; height: 28px; border-radius: 6px;
            background: rgba(255,255,255,0.2); border: none;
            color: #fff; cursor: pointer; font-size: 18px;
        }
        .ai-panel-close:hover { background: rgba(255,255,255,0.3); }
        .ai-panel-body { padding: 16px; }
        .ai-prompt-input {
            width: 100%; height: 120px; background: #16213e; border: 1px solid #0f3460;
            border-radius: 8px; padding: 12px; color: #fff; font-size: 14px;
            resize: none; outline: none;
        }
        .ai-prompt-input:focus { border-color: #667eea; }
        .ai-panel-footer {
            padding: 12px 16px; background: #16213e;
            display: flex; align-items: center; justify-content: flex-end; gap: 12px;
        }
        .ai-loading-text { color: #888; font-size: 13px; }
    </style>
    <link rel="stylesheet" href="/static/lib/highlight-default.min.css">
    <link rel="stylesheet" href="/static/css/style.css">
    <link rel="stylesheet" href="/static/lib/xterm.css">
    <script src="/static/lib/highlight.min.js"></script>
    <script src="/static/js/clipboard.min.js"></script>
    <script src="/static/js/globals.js"></script>
    <script src="/static/lib/socket.io.min.js"></script>
    <script src="/static/lib/xterm.js"></script>
    <script src="/static/lib/xterm-addon-fit.js"></script>
<link rel="stylesheet" href="/static/lib/sweetalert2.min.css">
<script src="/static/lib/sweetalert2.min.js"></script>
</head>
<body>
    <div class="editor-header">
        <a href="#" class="editor-btn" onclick="__confirmAndGoBack(); return false;">←</a>
        <div class="editor-title-wrap">
            <h1 class="editor-title" id="editorTitleText">{{ filename }}:0</h1>
            <button id="editorRefBtn" class="editor-btn" type="button" title="复制引用" onmousedown="event.preventDefault()">引用</button>
        </div>
    </div>

    <div class="editor-container">
        <div class="floating-buttons">
            <button class="editor-btn" onclick="openAiPanel()" title="AI 生成代码">✨</button>
            <button class="editor-btn" onclick="TerminalLib.open('{{ current_dir }}', '{{ file_path }}')" title="终端">📺</button>
            <button class="editor-btn" onclick="undo()">↩</button>
            <button class="editor-btn" onclick="redo()">↪</button>
            <button class="editor-btn" onclick="saveFile()">💾</button>
        </div>
        <textarea id="editor">{{ content }}</textarea>
    </div>

    <div id="toastContainer" class="toast-container"></div>

    <!-- AI Panel -->
    <div id="aiPanel" class="ai-panel" style="display:none;">
        <div class="ai-panel-backdrop" onclick="closeAiPanel()"></div>
        <div class="ai-panel-content">
            <div class="ai-panel-header">
                <span>AI 代码助手</span>
                <button class="ai-panel-close" onclick="closeAiPanel()">×</button>
            </div>
            <div class="ai-panel-body">
                <textarea id="aiPromptInput" class="ai-prompt-input"
                          placeholder="输入自然语言，让 AI 生成或修改代码..."></textarea>
            </div>
            <div class="ai-panel-footer">
                <span class="ai-loading-text" id="aiLoadingText" style="display:none;">AI 生成中...</span>
                <button class="editor-btn" onclick="generateCodeFromAi()" id="aiGenerateBtn">生成代码</button>
            </div>
        </div>
    </div>

    <script>
        // 根据文件类型设置编辑器模式
        var modeMap = {
            'py': 'python',
            'js': 'javascript',
            'html': 'htmlmixed',
            'htm': 'htmlmixed',
            'css': 'css',
            'json': 'javascript',
            'xml': 'xml',
            'md': 'markdown',
            'markdown': 'markdown',
            'txt': 'text'
        };

        var ext = '{{ extension }}'.substring(1); // 移除点号
        var mode = modeMap[ext] || 'text';

        // 初始化编辑器
        var editor = CodeMirror.fromTextArea(document.getElementById("editor"), {
            mode: mode,
            theme: "default",
            lineNumbers: true,
            styleActiveLine: true,
            matchBrackets: true,
            autoCloseBrackets: true,
            foldGutter: true,
            gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
            keyMap: "sublime",
            extraKeys: {
                "Ctrl-S": function(cm) { saveFile(); },
                "Cmd-S": function(cm) { saveFile(); },
                "Ctrl-Z": function(cm) { undo(); },
                "Cmd-Z": function(cm) { undo(); },
                "Ctrl-Y": function(cm) { redo(); },
                "Cmd-Y": function(cm) { redo(); },
                "Ctrl-/": "toggleComment",
                "Cmd-/": "toggleComment",
                "Ctrl-[": "indentLess",
                "Ctrl-]": "indentMore",
                "Ctrl-Shift-F": function(cm) { formatCode(); }
            }
        });

        var __baseFilename = {{ filename|tojson }};
        var __relPath = {{ file_path|tojson }};
        var __editorHasFocus = false;
        var __currentLine = 0;
        var __dirty = false;
        var __titleEl = document.getElementById('editorTitleText');
        var __refBtn = document.getElementById('editorRefBtn');
        var __rafPending = false;
        var __refClipboard = null;

        function __isSafeRelPath(p) {
            if (typeof p !== 'string') return false;
            var s = p.replace(/\\/g, '/').trim();
            if (!s) return false;
            if (s.indexOf(':') !== -1) return false;
            if (s.startsWith('/') || s.startsWith('\\')) return false;
            if (s === '.' || s.startsWith('./') || s.startsWith('../') || s.indexOf('/../') !== -1) return false;
            return true;
        }

        function __updateRefBtnState() {
            if (!__refBtn) return;
            if (!__baseFilename) {
                __refBtn.disabled = true;
                __refBtn.title = '无打开文件';
                return;
            }
            if (!__isSafeRelPath(__relPath)) {
                __refBtn.disabled = true;
                __refBtn.title = 'root-dir 解析失败';
                return;
            }
            if (__dirty) {
                __refBtn.disabled = true;
                __refBtn.title = '文件未保存';
                return;
            }
            __refBtn.disabled = false;
            __refBtn.title = '复制引用';
        }

        function __computeLine() {
            try {
                var c = editor.getCursor();
                if (!c || typeof c.line !== 'number') return 0;
                return c.line + 1;
            } catch (e) {
                return __currentLine || 0;
            }
        }

        function __updateTitleNow() {
            __currentLine = __computeLine();
            if (__titleEl) __titleEl.textContent = (__baseFilename || 'title.txt') + ':' + __currentLine;
            __updateRefBtnState();
        }

        function __scheduleTitleUpdate() {
            if (__rafPending) return;
            __rafPending = true;
            requestAnimationFrame(function() {
                __rafPending = false;
                __updateTitleNow();
            });
        }

        editor.on('focus', function() {
            __editorHasFocus = true;
            __scheduleTitleUpdate();
        });
        editor.on('blur', function() {
            __editorHasFocus = false;
            __scheduleTitleUpdate();
        });
        editor.on('cursorActivity', __scheduleTitleUpdate);
        editor.on('change', function() {
            __dirty = true;
            __updateRefBtnState();
        });
        __updateTitleNow();

        function __flashRefBtn(kind) {
            if (!__refBtn) return;
            __refBtn.classList.remove('copied');
            __refBtn.classList.remove('copy-failed');
            __refBtn.classList.add(kind);
            setTimeout(function() {
                if (__refBtn) __refBtn.classList.remove(kind);
            }, 450);
        }

        function __computeLineForReference() {
            try {
                var c = editor.getCursor();
                if (c && typeof c.line === 'number') return c.line + 1;
            } catch (e) {}
            return __currentLine || 0;
        }

        function __getReferenceText() {
            var line = __computeLineForReference();
            if (line > 0) __currentLine = line;
            if (__titleEl) __titleEl.textContent = (__baseFilename || 'title.txt') + ':' + (__currentLine || 0);
            __updateRefBtnState();
            return __relPath + ':' + (__currentLine || 0);
        }

        function __initReferenceCopy() {
            if (!__refBtn) return;

            __refBtn.setAttribute('tabindex', '-1');

            function __keepEditorFocus(e) {
                if (e) {
                    if (typeof e.preventDefault === 'function') e.preventDefault();
                    if (typeof e.stopPropagation === 'function') e.stopPropagation();
                }
                try { editor.focus(); } catch (e2) {}
            }

            __refBtn.addEventListener('pointerdown', __keepEditorFocus, { passive: false });
            __refBtn.addEventListener('mousedown', __keepEditorFocus, { passive: false });
            __refBtn.addEventListener('click', __keepEditorFocus, { passive: false });

            if (typeof ClipboardJS !== 'function') return;
            if (__refClipboard && typeof __refClipboard.destroy === 'function') {
                __refClipboard.destroy();
                __refClipboard = null;
            }
            __refClipboard = new ClipboardJS(__refBtn, {
                text: function() {
                    return __getReferenceText();
                }
            });
            __refClipboard.on('success', function() {
                __flashRefBtn('copied');
                if (window.showToast) window.showToast('已复制', 'success');
            });
            __refClipboard.on('error', function() {
                __flashRefBtn('copy-failed');
                if (window.showToast) window.showToast('复制失败', 'error');
            });
        }

        function saveFile() {
            const content = editor.getValue();
            const statusDiv = document.getElementById('saveStatus');

            fetch('/save_file/{{ file_path|urlencode }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ content: content })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    __dirty = false;
                    __updateRefBtnState();
                    statusDiv.textContent = '文件保存成功！';
                    statusDiv.className = 'save-status save-success';
                    statusDiv.style.display = 'block';

                    // 显示成功提示
                    Swal.fire({ icon: 'success', title: '保存成功', timer: 2000 });

                    setTimeout(() => {
                        statusDiv.style.display = 'none';
                    }, 3000);
                } else {
                    statusDiv.textContent = '保存失败: ' + data.message;
                    statusDiv.className = 'save-status save-error';
                    statusDiv.style.display = 'block';

                    // 显示失败提示
                    Swal.fire({ icon: 'error', title: '保存失败', text: data.message });
                }
            })
            .catch(error => {
                statusDiv.textContent = '保存时发生错误: ' + error;
                statusDiv.className = 'save-status save-error';
                statusDiv.style.display = 'block';

                // 显示错误提示
                Swal.fire({ icon: 'error', title: '保存错误', text: error });
            });
        }

        function undo() {
            editor.undo();
        }

        function redo() {
            editor.redo();
        }

        function formatCode() {
            // 对于支持的模式，提供基本的格式化功能
            // 在实际应用中，这里可以集成更高级的格式化工具
            Swal.fire({ icon: 'info', title: '格式化', text: '格式化功能已触发。对于Python/JS/HTML/CSS等文件，可以集成prettier、black等格式化工具。' });
        }

        // 自动调整编辑器大小
        window.addEventListener('resize', function() {
            editor.setSize(null, 'calc(100vh - 40px)');
        });

        // 页面加载时应用保存的字体大小
        const savedFontSize = localStorage.getItem('pywebdeck_font_size') || '14';
        document.documentElement.style.setProperty('--global-font-size', savedFontSize + 'px');

        async function __confirmAndGoBack() {
            if (__dirty) { // 检查是否有未保存的更改
                const r = await Swal.fire({ 
                    icon: "warning", 
                    title: "未保存的更改", 
                    text: "确定要离开吗？",
                    showDenyButton: true,
                    showCancelButton: true,
                    confirmButtonText: "保存",
                    denyButtonText: "不保存",
                    cancelButtonText: "取消"
                });
                if (r.isConfirmed) {
                    // 用户点击"保存"
                    await saveFile();
                    history.back();
                } else if (r.isDenied) {
                    // 用户点击"不保存"
                    history.back();
                } else {
                    // 用户点击"取消"，什么都不做
                    return;
                }
            } else {
                // 没有未保存的更改，直接返回
                history.back();
            }
        }

        __initReferenceCopy();
    </script>

    <script>
        // AI 代码助手
        function openAiPanel() {
            document.getElementById('aiPanel').style.display = 'flex';
            document.getElementById('aiPromptInput').focus();
        }

        function closeAiPanel() {
            document.getElementById('aiPanel').style.display = 'none';
        }

        async function generateCodeFromAi() {
            const prompt = document.getElementById('aiPromptInput').value.trim();
            const currentCode = editor.getValue();
            const filename = '{{ filename }}';

            if (!prompt) {
                Swal.fire({ icon: 'warning', title: '提示', text: '请输入 prompt' });
                return;
            }

            const btn = document.getElementById('aiGenerateBtn');
            const loadingText = document.getElementById('aiLoadingText');
            btn.disabled = true;
            btn.textContent = '生成中...';
            loadingText.style.display = 'inline';

            try {
                const response = await fetch('/code_editor/ai-generate', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        prompt: prompt,
                        code: currentCode,
                        filename: filename
                    })
                });

                const data = await response.json();

                if (data.success && data.code) {
                    editor.setValue(data.code);
                    closeAiPanel();
                    __dirty = true;
                    __updateRefBtnState();
                } else {
                    Swal.fire({ icon: 'error', title: '生成失败', text: data.message || data.error || '未知错误' });
                }
            } catch (e) {
                Swal.fire({ icon: 'error', title: '生成错误', text: e.message });
            } finally {
                btn.disabled = false;
                btn.textContent = '生成代码';
                loadingText.style.display = 'none';
            }
        }

        // Ctrl+Enter 提交 AI Prompt
        var aiPromptInput = document.getElementById('aiPromptInput');
        if (aiPromptInput) {
            aiPromptInput.addEventListener('keydown', function(e) {
                if (e.ctrlKey && e.key === 'Enter') {
                    e.preventDefault();
                    generateCodeFromAi();
                }
            });
        }
    </script>


    <!-- Terminal Library -->
    <script src="/static/js/terminal_lib.js"></script>
</body>
</html>
