// ==UserScript==
// @name         Illusion
// @icon         https://raw.githubusercontent.com/cattail-mutt/Illusion/refs/heads/main/image/icons/illusion.png
// @namespace    https://github.com/cattail-mutt
// @version      1.5
// @description  Illusion(幻觉)是一个跨平台 Prompts 管理工具,支持在以下平台使用:Google AI Studio, ChatGPT, Claude, Grok 和 DeepSeek
// @author       Mukai
// @license      MIT
// @match        https://aistudio.google.com/*
// @match        https://chatgpt.com/*
// @match        https://claude.ai/*
// @match        https://chat.deepseek.com/*
// @match        https://grok.com/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_getResourceText
// @resource     PROMPTS https://raw.githubusercontent.com/cattail-mutt/Illusion/refs/heads/main/prompt/prompts.json
// @resource     THEMES https://raw.githubusercontent.com/cattail-mutt/Illusion/refs/heads/main/style/themes.json
// @resource     CSS https://raw.githubusercontent.com/cattail-mutt/Illusion/refs/heads/main/style/illusion.css
// @homepage     https://greasyfork.org/zh-CN/scripts/527451-%E5%B9%BB%E8%A7%89-illusion
// @downloadURL https://update.greasyfork.icu/scripts/527451/Illusion.user.js
// @updateURL https://update.greasyfork.icu/scripts/527451/Illusion.meta.js
// ==/UserScript==
(function() {
    'use strict';
    const debug = {
        enabled: true,
        log: (...args) => debug.enabled && console.log('> Illusion 日志:', ...args),
        error: (...args) => console.error('> Illusion 错误:', ...args)
    };
    let modalRef = null;
    let overlayRef = null;
    let savedPrompts = {};
    const initialPrompts = JSON.parse(GM_getResourceText('PROMPTS'));
    const promptsObject = Object.fromEntries(
    (initialPrompts || [])
            .filter(item => item?.id && item?.value)
            .map(item => [item.id, item.value])
    );
    console.log('PROMPTS解析结果:', promptsObject);
    const THEMECONFIG = JSON.parse(GM_getResourceText('THEMES'));
    debug.log('THEMES解析结果:', THEMECONFIG);
    function dispatchEvents(element, events) {
        events.forEach(eventName => {
            const event = eventName === 'input' 
                ? new InputEvent(eventName, { bubbles: true }) 
                : new Event(eventName, { bubbles: true });
            element.dispatchEvent(event);
        });
    }
    function createParagraph(line) {
        const p = document.createElement('p');
        if (line.trim()) {
            p.textContent = line;
        } else {
            p.innerHTML = '
';
        }
        return p;
    }
    const updateProseMirror = (editor, prompt) => {  // ChatGPT 和 Claude 均使用了 ProseMirror 库构建富文本编辑器
        const paragraphs = Array.from(editor.querySelectorAll('p'));
        let currentContent = '';
        paragraphs.forEach(p => {
            const text = p.textContent.trim();
            if (text) {
                currentContent += text + '\n';
            } else {
                currentContent += '\n';
            }
        });
        let newContent = currentContent.trim();
        if (newContent) {
            newContent += '\n';
        }
        editor.innerHTML = '';
        if (newContent) {
            newContent.split('\n').forEach(line => {
                editor.appendChild(createParagraph(line));
            });
        }
        const lines = prompt.split('\n');
        lines.forEach((line, index) => {
            editor.appendChild(createParagraph(line));
            if (index < lines.length - 1 && !line.trim()) {
                const brP = document.createElement('p');
                brP.innerHTML = '
';
                editor.appendChild(brP);
            }
        });
        dispatchEvents(editor, ['input', 'change']);
    };
    const updateTextArea = async (textarea, prompt) => {  // Gemini 和 DeepSeek 使用的均是纯文本输入框