<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>码字工坊 - 自动保存写作平台</title>
    <style>
        :root {
            --bg-primary: #f5f3f0;
            --bg-secondary: #e8e4de;
            --bg-sidebar: #faf8f5;
            --text-primary: #2c2c2c;
            --text-secondary: #666;
            --text-muted: #999;
            --accent: #c75c3a;
            --accent-hover: #a84a2d;
            --border: #d4cfc7;
            --shadow: rgba(0,0,0,0.08);
            --editor-bg: #fcfaf7;
            --success: #4a9e5c;
            --warning: #d4a017;
        }

        [data-theme="dark"] {
            --bg-primary: #1a1a1a;
            --bg-secondary: #252525;
            --bg-sidebar: #202020;
            --text-primary: #e0e0e0;
            --text-secondary: #aaa;
            --text-muted: #666;
            --accent: #d4765a;
            --accent-hover: #b85d42;
            --border: #333;
            --shadow: rgba(0,0,0,0.3);
            --editor-bg: #1e1e1e;
            --success: #5cb85c;
            --warning: #f0ad4e;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
            background: var(--bg-primary);
            color: var(--text-primary);
            height: 100vh;
            overflow: hidden;
            transition: background 0.3s, color 0.3s;
        }

        /* 布局 */
        .app {
            display: flex;
            height: 100vh;
        }

        /* 侧边栏 */
        .sidebar {
            width: 280px;
            background: var(--bg-sidebar);
            border-right: 1px solid var(--border);
            display: flex;
            flex-direction: column;
            transition: all 0.3s;
        }

        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid var(--border);
        }

        .logo {
            font-size: 20px;
            font-weight: 700;
            color: var(--accent);
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .logo::before {
            content: "✦";
            font-size: 24px;
        }

        .new-btn {
            width: 100%;
            padding: 10px;
            background: var(--accent);
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
            transition: background 0.2s;
            font-weight: 500;
        }

        .new-btn:hover {
            background: var(--accent-hover);
        }

        .search-box {
            margin-top: 12px;
            position: relative;
        }

        .search-box input {
            width: 100%;
            padding: 8px 12px 8px 32px;
            border: 1px solid var(--border);
            border-radius: 6px;
            background: var(--bg-primary);
            color: var(--text-primary);
            font-size: 13px;
            outline: none;
        }

        .search-box::before {
            content: "🔍";
            position: absolute;
            left: 10px;
            top: 50%;
            transform: translateY(-50%);
            opacity: 0.5;
            font-size: 12px;
        }

        .article-list {
            flex: 1;
            overflow-y: auto;
            padding: 8px;
        }

        .article-item {
            padding: 12px;
            border-radius: 6px;
            cursor: pointer;
            margin-bottom: 4px;
            transition: all 0.2s;
            border-left: 3px solid transparent;
        }

        .article-item:hover {
            background: var(--bg-secondary);
        }

        .article-item.active {
            background: var(--bg-secondary);
            border-left-color: var(--accent);
        }

        .article-title {
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 4px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .article-meta {
            font-size: 11px;
            color: var(--text-muted);
            display: flex;
            justify-content: space-between;
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: var(--text-muted);
            font-size: 13px;
        }

        /* 主编辑区 */
        .main {
            flex: 1;
            display: flex;
            flex-direction: column;
            min-width: 0;
        }

        .toolbar {
            height: 56px;
            background: var(--bg-sidebar);
            border-bottom: 1px solid var(--border);
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 24px;
            gap: 12px;
        }

        .toolbar-left {
            display: flex;
            align-items: center;
            gap: 12px;
            flex: 1;
        }

        .toolbar-right {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .title-input {
            font-size: 16px;
            font-weight: 600;
            border: none;
            background: transparent;
            color: var(--text-primary);
            outline: none;
            width: 100%;
            max-width: 400px;
            padding: 4px 0;
            border-bottom: 2px solid transparent;
            transition: border-color 0.2s;
        }

        .title-input:focus {
            border-bottom-color: var(--accent);
        }

        .save-status {
            font-size: 12px;
            color: var(--text-muted);
            display: flex;
            align-items: center;
            gap: 6px;
            min-width: 120px;
        }

        .save-status.saving { color: var(--warning); }
        .save-status.saved { color: var(--success); }
        .save-status.error { color: #d9534f; }

        .status-dot {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: currentColor;
            display: inline-block;
        }

        .btn-icon {
            width: 32px;
            height: 32px;
            border: 1px solid var(--border);
            background: transparent;
            border-radius: 6px;
            cursor: pointer;
            color: var(--text-secondary);
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
            font-size: 14px;
        }

        .btn-icon:hover {
            background: var(--bg-secondary);
            color: var(--text-primary);
        }

        .btn-text {
            padding: 0 12px;
            height: 32px;
            border: 1px solid var(--border);
            background: transparent;
            border-radius: 6px;
            cursor: pointer;
            color: var(--text-secondary);
            font-size: 13px;
            transition: all 0.2s;
        }

        .btn-text:hover {
            background: var(--bg-secondary);
            color: var(--text-primary);
        }

        /* 编辑器 */
        .editor-container {
            flex: 1;
            overflow-y: auto;
            padding: 40px 0;
            background: var(--editor-bg);
        }

        .editor-wrapper {
            max-width: 800px;
            margin: 0 auto;
            padding: 0 40px;
        }

        .editor {
            width: 100%;
            min-height: 70vh;
            border: none;
            outline: none;
            background: transparent;
            color: var(--text-primary);
            font-size: 18px;
            line-height: 1.8;
            font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
            resize: none;
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        .editor::placeholder {
            color: var(--text-muted);
            opacity: 0.5;
        }

        /* 统计栏 */
        .stats-bar {
            height: 36px;
            background: var(--bg-sidebar);
            border-top: 1px solid var(--border);
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 24px;
            font-size: 12px;
            color: var(--text-muted);
        }

        .stats-left {
            display: flex;
            gap: 20px;
        }

        .stat-item {
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .stat-value {
            font-weight: 600;
            color: var(--text-primary);
        }

        /* 全屏模式 */
        .fullscreen .sidebar,
        .fullscreen .toolbar,
        .fullscreen .stats-bar {
            display: none;
        }

        .fullscreen .main {
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            z-index: 1000;
            background: var(--editor-bg);
        }

        .fullscreen .editor-container {
            padding: 60px 0;
        }

        .exit-fullscreen {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1001;
            padding: 8px 16px;
            background: var(--accent);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 13px;
            opacity: 0;
            transition: opacity 0.3s;
        }

        .fullscreen .exit-fullscreen {
            opacity: 1;
        }

        /* 提示 */
        .toast {
            position: fixed;
            bottom: 60px;
            left: 50%;
            transform: translateX(-50%) translateY(20px);
            background: var(--text-primary);
            color: var(--bg-primary);
            padding: 10px 20px;
            border-radius: 8px;
            font-size: 13px;
            opacity: 0;
            transition: all 0.3s;
            pointer-events: none;
            z-index: 2000;
        }

        .toast.show {
            opacity: 1;
            transform: translateX(-50%) translateY(0);
        }

        /* 确认对话框 */
        .modal-overlay {
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(0,0,0,0.5);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 3000;
        }

        .modal-overlay.show {
            display: flex;
        }

        .modal {
            background: var(--bg-sidebar);
            border-radius: 12px;
            padding: 24px;
            width: 360px;
            box-shadow: 0 20px 60px var(--shadow);
        }

        .modal-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 8px;
        }

        .modal-text {
            font-size: 13px;
            color: var(--text-secondary);
            margin-bottom: 20px;
        }

        .modal-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 8px;
        }

        .modal-btn {
            padding: 8px 16px;
            border-radius: 6px;
            border: 1px solid var(--border);
            background: transparent;
            cursor: pointer;
            font-size: 13px;
            transition: all 0.2s;
        }

        .modal-btn.primary {
            background: var(--accent);
            color: white;
            border-color: var(--accent);
        }

        .modal-btn:hover {
            opacity: 0.9;
        }

        /* 滚动条 */
        ::-webkit-scrollbar {
            width: 6px;
        }

        ::-webkit-scrollbar-track {
            background: transparent;
        }

        ::-webkit-scrollbar-thumb {
            background: var(--border);
            border-radius: 3px;
        }

        /* 响应式 */
        @media (max-width: 768px) {
            .sidebar {
                position: fixed;
                left: -280px;
                top: 0;
                bottom: 0;
                z-index: 100;
                box-shadow: 2px 0 10px var(--shadow);
            }

            .sidebar.open {
                left: 0;
            }

            .mobile-menu-btn {
                display: flex !important;
            }

            .editor-wrapper {
                padding: 0 20px;
            }
        }

        .mobile-menu-btn {
            display: none;
        }

        /* 动画 */
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }

        .saving .status-dot {
            animation: pulse 1s infinite;
        }
    </style>
</head>
<body>
    <div class="app" id="app">
        <!-- 侧边栏 -->
        <aside class="sidebar" id="sidebar">
            <div class="sidebar-header">
                <div class="logo">码字工坊</div>
                <button class="new-btn" onclick="newArticle()">+ 新建文档</button>
                <div class="search-box">
                    <input type="text" id="searchInput" placeholder="搜索文档..." oninput="filterArticles()">
                </div>
            </div>
            <div class="article-list" id="articleList">
                <div class="empty-state">加载中...</div>
            </div>
        </aside>

        <!-- 主区域 -->
        <main class="main">
            <div class="toolbar">
                <div class="toolbar-left">
                    <button class="btn-icon mobile-menu-btn" onclick="toggleSidebar()" style="display:none">☰</button>
                    <input type="text" class="title-input" id="titleInput" placeholder="无标题文档" oninput="onTitleChange()">
                    <span class="save-status" id="saveStatus">
                        <span class="status-dot"></span>
                        <span id="saveText">就绪</span>
                    </span>
                </div>
                <div class="toolbar-right">
                    <button class="btn-icon" onclick="toggleTheme()" title="切换主题">◐</button>
                    <button class="btn-icon" onclick="toggleFullscreen()" title="专注模式">⛶</button>
                    <button class="btn-text" onclick="exportArticle('txt')">导出TXT</button>
                    <button class="btn-text" onclick="exportArticle('md')">导出MD</button>
                    <button class="btn-icon" onclick="deleteCurrent()" title="删除">🗑</button>
                </div>
            </div>

            <div class="editor-container" id="editorContainer">
                <div class="editor-wrapper">
                    <textarea class="editor" id="editor" placeholder="开始写作..." oninput="onEditorInput()"></textarea>
                </div>
            </div>

            <div class="stats-bar">
                <div class="stats-left">
                    <span class="stat-item">字数：<span class="stat-value" id="wordCount">0</span></span>
                    <span class="stat-item">字符：<span class="stat-value" id="charCount">0</span></span>
                    <span class="stat-item">时长：<span class="stat-value" id="writeTime">0</span> 分钟</span>
                </div>
                <div>自动保存已开启</div>
            </div>
        </main>
    </div>

    <button class="exit-fullscreen" onclick="toggleFullscreen()">退出专注模式 (Esc)</button>

    <div class="toast" id="toast"></div>

    <div class="modal-overlay" id="modal">
        <div class="modal">
            <div class="modal-title" id="modalTitle">确认</div>
            <div class="modal-text" id="modalText">确定要执行此操作吗？</div>
            <div class="modal-buttons">
                <button class="modal-btn" onclick="closeModal()">取消</button>
                <button class="modal-btn primary" id="modalConfirm" onclick="confirmModal()">确定</button>
            </div>
        </div>
    </div>

    <script>
        // 状态管理
        let currentId = '';
        let currentTitle = '';
        let currentContent = '';
        let isSaving = false;
        let saveTimer = null;
        let autoSaveTimer = null;
        let wordCount = 0;
        let startTime = Date.now();
        let writeTimeInterval = null;
        let articles = [];
        let modalCallback = null;
        let lastSavedContent = '';

        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            loadArticles();
            startWriteTimer();

            // 每30秒强制保存
            autoSaveTimer = setInterval(() => {
                if (currentId && currentContent !== lastSavedContent) {
                    saveArticle();
                }
            }, 30000);

            // 页面关闭前保存
            window.addEventListener('beforeunload', (e) => {
                if (currentContent !== lastSavedContent) {
                    saveArticle();
                    e.preventDefault();
                    e.returnValue = '';
                }
            });

            // 键盘快捷键
            document.addEventListener('keydown', (e) => {
                // Ctrl/Cmd + S
                if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                    e.preventDefault();
                    saveArticle();
                }
                // Esc 退出全屏
                if (e.key === 'Escape') {
                    document.body.classList.remove('fullscreen');
                }
            });

            // 恢复本地草稿
            restoreLocalDraft();
        });

        // 编辑器输入处理
        function onEditorInput() {
            const editor = document.getElementById('editor');
            currentContent = editor.value;
            updateStats();
            updateSaveStatus('saving', '保存中...');

            // 清除之前的定时器
            if (saveTimer) clearTimeout(saveTimer);

            // 停止输入2秒后自动保存
            saveTimer = setTimeout(() => {
                saveArticle();
            }, 2000);

            // 保存本地草稿
            saveLocalDraft();
        }

        function onTitleChange() {
            currentTitle = document.getElementById('titleInput').value;
            if (saveTimer) clearTimeout(saveTimer);
            saveTimer = setTimeout(() => {
                saveArticle();
            }, 2000);
        }

        // 保存文章
        async function saveArticle() {
            if (isSaving || !currentId) return;
            if (currentContent === lastSavedContent && currentTitle === (articles.find(a => a.id === currentId)?.title || '')) {
                updateSaveStatus('saved', '已保存');
                return;
            }

            isSaving = true;
            updateSaveStatus('saving', '保存中...');

            try {
                const formData = new FormData();
                formData.append('action', 'save');
                formData.append('id', currentId);
                formData.append('title', currentTitle || '未命名文档');
                formData.append('content', currentContent);
                formData.append('wordCount', wordCount);

                const response = await fetch('', {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    lastSavedContent = currentContent;
                    updateSaveStatus('saved', `已保存 ${data.savedAt.split(' ')[1]}`);
                    updateArticleInList(currentId, currentTitle, wordCount, data.savedAt);
                    clearLocalDraft(currentId);
                } else {
                    throw new Error(data.error);
                }
            } catch (err) {
                updateSaveStatus('error', '保存失败');
                showToast('保存失败：' + err.message);
                // 保留本地草稿
            } finally {
                isSaving = false;
            }
        }

        // 加载文章列表
        async function loadArticles() {
            try {
                const response = await fetch('?action=list');
                const data = await response.json();
                articles = data.articles || [];
                renderArticleList();

                // 如果有文章，加载第一篇
                if (articles.length > 0) {
                    loadArticle(articles[0].id);
                } else {
                    newArticle();
                }
            } catch (err) {
                showToast('加载失败：' + err.message);
            }
        }

        function renderArticleList() {
            const list = document.getElementById('articleList');
            const search = document.getElementById('searchInput').value.toLowerCase();

            const filtered = articles.filter(a => 
                a.title.toLowerCase().includes(search)
            );

            if (filtered.length === 0) {
                list.innerHTML = '<div class="empty-state">暂无文档<br>点击上方按钮创建</div>';
                return;
            }

            list.innerHTML = filtered.map(article => `
                <div class="article-item ${article.id === currentId ? 'active' : ''}" 
                     onclick="loadArticle('${article.id}')" 
                     data-id="${article.id}">
                    <div class="article-title">${escapeHtml(article.title || '未命名')}</div>
                    <div class="article-meta">
                        <span>${article.wordCount} 字</span>
                        <span>${formatDate(article.updatedAt)}</span>
                    </div>
                </div>
            `).join('');
        }

        function filterArticles() {
            renderArticleList();
        }

        // 加载单篇文章
        async function loadArticle(id) {
            // 先保存当前
            if (currentId && currentContent !== lastSavedContent) {
                await saveArticle();
            }

            try {
                const response = await fetch(`?action=load&id=${id}`);
                const data = await response.json();

                if (data.article) {
                    const article = data.article;
                    currentId = article.id;
                    currentTitle = article.title;
                    currentContent = article.content;
                    lastSavedContent = article.content;
                    wordCount = article.wordCount || 0;

                    document.getElementById('titleInput').value = article.title;
                    document.getElementById('editor').value = article.content;
                    updateStats();
                    updateSaveStatus('saved', `已保存 ${article.updatedAt.split(' ')[1]}`);

                    renderArticleList();

                    // 移动端关闭侧边栏
                    if (window.innerWidth <= 768) {
                        document.getElementById('sidebar').classList.remove('open');
                    }
                }
            } catch (err) {
                showToast('加载失败：' + err.message);
            }
        }

        // 新建文章
        function newArticle() {
            if (currentId && currentContent !== lastSavedContent) {
                saveArticle();
            }

            currentId = '';
            currentTitle = '';
            currentContent = '';
            lastSavedContent = '';
            wordCount = 0;
            startTime = Date.now();

            document.getElementById('titleInput').value = '';
            document.getElementById('editor').value = '';
            updateStats();
            updateSaveStatus('saved', '就绪');

            // 生成新ID并保存
            currentId = generateId();
            saveArticle();

            // 添加到列表
            const newArticle = {
                id: currentId,
                title: '未命名文档',
                wordCount: 0,
                updatedAt: new Date().toISOString(),
                createdAt: new Date().toISOString()
            };
            articles.unshift(newArticle);
            renderArticleList();
        }

        // 删除文章
        function deleteCurrent() {
            if (!currentId) return;
            if (articles.length <= 1) {
                showToast('至少需要保留一篇文档');
                return;
            }

            showModal('删除文档', `确定要删除「${currentTitle || '未命名'}」吗？此操作不可恢复。`, async () => {
                try {
                    const formData = new FormData();
                    formData.append('action', 'delete');
                    formData.append('id', currentId);

                    await fetch('', { method: 'POST', body: formData });

                    articles = articles.filter(a => a.id !== currentId);
                    renderArticleList();

                    if (articles.length > 0) {
                        loadArticle(articles[0].id);
                    } else {
                        newArticle();
                    }

                    showToast('已删除');
                } catch (err) {
                    showToast('删除失败');
                }
            });
        }

        // 导出
        function exportArticle(format) {
            if (!currentId) return;
            window.open(`?action=export&id=${currentId}&format=${format}`, '_blank');
        }

        // 更新列表中的文章
        function updateArticleInList(id, title, wc, updatedAt) {
            const idx = articles.findIndex(a => a.id === id);
            if (idx >= 0) {
                articles[idx].title = title;
                articles[idx].wordCount = wc;
                articles[idx].updatedAt = updatedAt;
                // 移到顶部
                const article = articles.splice(idx, 1)[0];
                articles.unshift(article);
                renderArticleList();
            }
        }

        // 统计
        function updateStats() {
            const text = currentContent;
            // 中文字符 + 英文单词
            const cnChars = (text.match(/[\u4e00-\u9fa5]/g) || []).length;
            const enWords = (text.match(/[a-zA-Z]+/g) || []).length;
            wordCount = cnChars + enWords;

            document.getElementById('wordCount').textContent = wordCount;
            document.getElementById('charCount').textContent = text.length;
        }

        function startWriteTimer() {
            writeTimeInterval = setInterval(() => {
                const mins = Math.floor((Date.now() - startTime) / 60000);
                document.getElementById('writeTime').textContent = mins;
            }, 60000);
        }

        // 保存状态显示
        function updateSaveStatus(status, text) {
            const el = document.getElementById('saveStatus');
            const txt = document.getElementById('saveText');
            el.className = 'save-status ' + status;
            txt.textContent = text;
        }

        // 主题切换
        function toggleTheme() {
            const html = document.documentElement;
            const current = html.getAttribute('data-theme');
            html.setAttribute('data-theme', current === 'dark' ? 'light' : 'dark');
            localStorage.setItem('theme', current === 'dark' ? 'light' : 'dark');
        }

        // 恢复主题
        const savedTheme = localStorage.getItem('theme');
        if (savedTheme) {
            document.documentElement.setAttribute('data-theme', savedTheme);
        }

        // 全屏
        function toggleFullscreen() {
            document.body.classList.toggle('fullscreen');
        }

        // 侧边栏（移动端）
        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('open');
        }

        // 本地草稿（双重保险）
        function saveLocalDraft() {
            if (!currentId) return;
            const drafts = JSON.parse(localStorage.getItem('writer_drafts') || '{}');
            drafts[currentId] = {
                title: currentTitle,
                content: currentContent,
                savedAt: new Date().toISOString()
            };
            localStorage.setItem('writer_drafts', JSON.stringify(drafts));
        }

        function restoreLocalDraft() {
            // 如果有服务器数据，不恢复本地草稿
            // 这个函数主要用于极端情况下的数据恢复
        }

        function clearLocalDraft(id) {
            const drafts = JSON.parse(localStorage.getItem('writer_drafts') || '{}');
            delete drafts[id];
            localStorage.setItem('writer_drafts', JSON.stringify(drafts));
        }

        // 工具函数
        function generateId() {
            return new Date().toISOString().slice(0,10).replace(/-/g,'') + '_' + 
                   Date.now().toString(36).slice(-6) + '_' + 
                   Math.random().toString(36).slice(-4);
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        function formatDate(dateStr) {
            const date = new Date(dateStr);
            const now = new Date();
            const diff = (now - date) / 1000;

            if (diff < 60) return '刚刚';
            if (diff < 3600) return Math.floor(diff/60) + '分钟前';
            if (diff < 86400) return Math.floor(diff/3600) + '小时前';
            return (date.getMonth()+1) + '-' + date.getDate();
        }

        // 提示
        function showToast(msg) {
            const toast = document.getElementById('toast');
            toast.textContent = msg;
            toast.classList.add('show');
            setTimeout(() => toast.classList.remove('show'), 3000);
        }

        // 对话框
        function showModal(title, text, callback) {
            document.getElementById('modalTitle').textContent = title;
            document.getElementById('modalText').textContent = text;
            document.getElementById('modal').classList.add('show');
            modalCallback = callback;
        }

        function closeModal() {
            document.getElementById('modal').classList.remove('show');
            modalCallback = null;
        }

        function confirmModal() {
            if (modalCallback) modalCallback();
            closeModal();
        }
    </script>
</body>
</html>
