document.addEventListener('DOMContentLoaded', function() {
    console.log("AI Admin Script Loaded v2");

    // 1. 寻找页面右上角的工具栏 (保持不变的逻辑)
    let objectTools = document.querySelector('ul.object-tools');
    if (!objectTools) {
        objectTools = document.createElement('ul');
        objectTools.className = 'object-tools';
        const contentTitle = document.querySelector('#content h1');
        if (contentTitle) {
            contentTitle.insertAdjacentElement('afterend', objectTools);
            objectTools.style.float = 'right';
            objectTools.style.marginTop = '-40px';
            objectTools.style.position = 'relative';
            objectTools.style.zIndex = '999';
        } else {
            const contentMain = document.getElementById('content-main');
            if (contentMain) {
                contentMain.insertBefore(objectTools, contentMain.firstChild);
            }
        }
    }

    // 2. 动态创建按钮 (保持不变)
    const li = document.createElement('li');
    const btn = document.createElement('a');
    btn.href = '#';
    btn.innerHTML = '🎨 AI 文生图';
    btn.className = 'historylink';
    btn.setAttribute('style', 'background-color: #0A76F7 !important; color: white !important; border-radius: 4px; padding: 5px 15px; text-decoration: none; display: inline-block;');
    li.appendChild(btn);
    objectTools.appendChild(li);

    // 3. 动态创建弹窗 HTML (界面大改版)
    const modalHtml = `
        <div id="ai-modal" style="display: none; position: fixed; z-index: 10000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.6); font-family: sans-serif;">
            <div style="background-color: #fff; margin: 6% auto; padding: 25px; border: 1px solid #888; width: 550px; max-width: 90%; border-radius: 12px; box-shadow: 0 10px 25px rgba(0,0,0,0.3);">
                <h2 style="margin-top:0; color: #333; font-size: 20px; border-bottom: 1px solid #eee; padding-bottom: 10px;">🎨 AI 配图生成器</h2>
                
                <div style="margin: 20px 0;">
                    <label style="display:block; margin-bottom: 8px; font-weight: bold; color: #555;">画面描述：</label>
                    <textarea id="ai-prompt-input" style="width: 100%; height: 90px; padding: 10px; border: 1px solid #ccc; border-radius: 6px; box-sizing: border-box; font-size: 14px; resize: vertical;" placeholder="例如：极简风格的风景画，雪山，日出..."></textarea>
                </div>
                
                <!-- 结果展示区 -->
                <div id="ai-result-area" style="margin-top: 15px; display:none; background: #f9f9f9; padding: 15px; border-radius: 6px; text-align: center;">
                    <p style="margin: 0 0 10px 0; color: green; font-weight: bold;">✅ 生成成功！</p>
                    
                    <!-- 预览图 -->
                    <div style="margin: 10px 0;">
                        <img id="ai-preview-img" src="" style="max-width: 100%; max-height: 280px; border-radius: 6px; border: 1px solid #eee; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                    </div>

                    <!-- 隐藏的输入框，用于存放Markdown路径供复制使用 -->
                    <input type="hidden" id="ai-hidden-url">

                    <!-- 操作按钮组 -->
                    <div style="display: flex; justify-content: center; gap: 15px; margin-top: 15px;">
                        <!-- 下载按钮 -->
                        <a id="ai-btn-download" href="#" target="_blank" download="ai_image.png" style="text-decoration: none; padding: 8px 18px; background-color: #28a745; color: white; border-radius: 4px; font-size: 14px; display: inline-flex; align-items: center;">
                            ⬇️ 下载图片
                        </a>

                        <!-- 复制链接按钮 -->
                        <button id="ai-btn-copy" style="padding: 8px 18px; background-color: #0A76F7; color: white; border: none; border-radius: 4px; font-size: 14px; cursor: pointer;">
                            📋 复制链接到文章
                        </button>
                    </div>
                </div>

                <div class="ai-loading" style="display: none; text-align: center; margin: 20px 0;">
                    <div style="display: inline-block; width: 20px; height: 20px; border: 3px solid #f3f3f3; border-top: 3px solid #0A76F7; border-radius: 50%; animation: spin 1s linear infinite;"></div>
                    <div style="color: #0A76F7; margin-top: 10px;">AI 正在绘图并传输，请稍候...</div>
                    <style>@keyframes spin {0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); }}</style>
                </div>

                <div style="text-align: right; margin-top: 25px; padding-top: 15px; border-top: 1px solid #eee;">
                    <button id="ai-btn-cancel" style="padding: 8px 20px; border: 1px solid #ddd; background-color: #fff; color: #333; border-radius: 4px; cursor: pointer; margin-right: 10px;">关闭</button>
                    <button id="ai-btn-confirm" style="padding: 8px 20px; border: none; background-color: #0A76F7; color: white; border-radius: 4px; cursor: pointer; font-weight: bold;">开始生成</button>
                </div>
            </div>
        </div>
    `;

    if (!document.getElementById('ai-modal')) {
        document.body.insertAdjacentHTML('beforeend', modalHtml);
    }

    // 4. 绑定事件逻辑
    const modal = document.getElementById('ai-modal');
    const loading = document.querySelector('.ai-loading');
    const resultArea = document.getElementById('ai-result-area');
    const promptInput = document.getElementById('ai-prompt-input');
    const previewImg = document.getElementById('ai-preview-img');
    const hiddenUrlInput = document.getElementById('ai-hidden-url');
    const downloadBtn = document.getElementById('ai-btn-download');
    const copyBtn = document.getElementById('ai-btn-copy');

    // 打开弹窗
    btn.addEventListener('click', function(e) {
        e.preventDefault();
        modal.style.display = 'block';
    });

    // 关闭弹窗
    document.getElementById('ai-btn-cancel').addEventListener('click', function(e) {
        e.preventDefault();
        modal.style.display = 'none';
        loading.style.display = 'none';
    });

    // 复制功能
    copyBtn.addEventListener('click', function(e) {
        e.preventDefault();
        if (hiddenUrlInput.value) {
            navigator.clipboard.writeText(hiddenUrlInput.value).then(() => {
                const originalText = copyBtn.innerText;
                copyBtn.innerText = '✅ 已复制！';
                copyBtn.style.backgroundColor = '#198754';
                setTimeout(() => {
                    copyBtn.innerText = originalText;
                    copyBtn.style.backgroundColor = '#0A76F7';
                }, 2000);
            });
        }
    });

    // 获取 Cookie
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // 生成逻辑
    document.getElementById('ai-btn-confirm').addEventListener('click', function(e) {
        e.preventDefault();
        const prompt = promptInput.value;
        if (!prompt) { alert('请输入描述！'); return; }

        loading.style.display = 'block';
        resultArea.style.display = 'none';

        // 重置按钮状态
        copyBtn.innerText = '📋 复制链接到文章';
        copyBtn.style.backgroundColor = '#0A76F7';

        fetch('/api/plugins/image/generate/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({prompt: prompt})
        })
        .then(response => response.json())
        .then(data => {
            loading.style.display = 'none';
            if (data.status === 'success') {
                resultArea.style.display = 'block';

                // 1. 设置预览图
                previewImg.src = data.url;

                // 2. 设置隐藏的 Markdown 用于复制
                const markdownUrl = "![](" + data.url + ")";
                hiddenUrlInput.value = markdownUrl;

                // 3. 设置下载按钮链接
                downloadBtn.href = data.url;
                // 尝试从 URL 提取文件名，例如 ai_123456.png
                const fileName = data.url.split('/').pop();
                downloadBtn.setAttribute('download', fileName);

            } else {
                alert('生成失败：' + data.message);
            }
        })
        .catch(error => {
            loading.style.display = 'none';
            alert('网络请求错误：' + error);
        });
    });
});