/**
 * MCP Feedback Enhanced - 主應用程式
 * =================================
 *
 * 模組化重構版本，整合所有功能模組
 * 依賴模組載入順序：utils -> tab-manager -> websocket-manager -> connection-monitor ->
 *                  session-manager -> image-handler -> settings-manager -> ui-manager ->
 *                  app
 */

(function() {
    'use strict';

    // 確保命名空間存在
    window.MCPFeedback = window.MCPFeedback || {};
    const Utils = window.MCPFeedback.Utils;

    /**
     * 主應用程式建構函數
     */
    function FeedbackApp(sessionId) {
        // 會話信息
        this.sessionId = sessionId;
        this.currentSessionId = null;

        // 模組管理器
        this.tabManager = null;
        this.webSocketManager = null;
        this.connectionMonitor = null;
        this.sessionManager = null;
        this.imageHandler = null;
        this.settingsManager = null;
        this.uiManager = null;

        // 提示詞管理器
        this.promptManager = null;
        this.promptModal = null;
        this.promptSettingsUI = null;
        this.promptInputButtons = null;

        // 音效管理器
        this.audioManager = null;
        this.audioSettingsUI = null;

        // 通知管理器
        this.notificationManager = null;
        this.notificationSettings = null;

        // 應用程式狀態
        this.isInitialized = false;
        this.pendingSubmission = null;

        // 初始化防抖函數
        this.initDebounceHandlers();

        console.log('🚀 FeedbackApp 建構函數初始化完成');
    }

    /**
     * 初始化防抖處理器
     */
    FeedbackApp.prototype.initDebounceHandlers = function() {
        // 先獲取 DOMUtils，如果不存在則跳過（開發模式下可能會有載入順序問題）
        const DOMUtils = window.MCPFeedback.DOMUtils || (window.MCPFeedback.Utils && window.MCPFeedback.Utils.DOM);
        
        if (!DOMUtils) {
            console.warn('⚠️ DOMUtils 未載入，延遲初始化防抖處理器');
            return;
        }
        
        // 為 WebSocket 訊息處理添加防抖
        this._debouncedHandleWebSocketMessage = DOMUtils.debounce(
            this._originalHandleWebSocketMessage.bind(this),
            50,
            false
        );

        // 為會話更新處理添加防抖
        this._debouncedHandleSessionUpdated = DOMUtils.debounce(
            this._originalHandleSessionUpdated.bind(this),
            100,
            false
        );

        // 為狀態更新處理添加防抖
        this._debouncedHandleStatusUpdate = DOMUtils.debounce(
            this._originalHandleStatusUpdate.bind(this),
            100,
            false
        );
    };

    /**
     * 初始化應用程式
     */
    FeedbackApp.prototype.init = function() {
        const self = this;

        console.log('🚀 初始化 MCP Feedback Enhanced 應用程式');

        return new Promise(function(resolve, reject) {
            try {
                // 等待國際化系統
                self.waitForI18n()
                    .then(function() {
                        return self.initializeManagers();
                    })
                    .then(function() {
                        return self.setupEventListeners();
                    })
                    .then(function() {
                        self.restoreFeedbackDraft();
                        return self.setupCleanupHandlers();
                    })
                    .then(function() {
                        self.isInitialized = true;
                        console.log('✅ MCP Feedback Enhanced 應用程式初始化完成');
                        resolve();
                    })
                    .catch(function(error) {
                        console.error('❌ 應用程式初始化失敗:', error);
                        reject(error);
                    });
            } catch (error) {
                console.error('❌ 應用程式初始化異常:', error);
                reject(error);
            }
        });
    };

    /**
     * 等待國際化系統載入
     */
    FeedbackApp.prototype.waitForI18n = function() {
        return new Promise(function(resolve) {
            if (window.i18nManager) {
                window.i18nManager.init().then(resolve).catch(resolve);
            } else {
                resolve();
            }
        });
    };

    /**
     * 初始化所有管理器
     */
    FeedbackApp.prototype.initializeManagers = function() {
        const self = this;

        return new Promise(function(resolve, reject) {
            try {
                console.log('🔧 初始化管理器...');

                // 1. 初始化設定管理器
                self.settingsManager = new window.MCPFeedback.SettingsManager({
                    onSettingsChange: function(settings) {
                        self.handleSettingsChange(settings);
                    },
                    onLanguageChange: function(language) {
                        self.handleLanguageChange(language);
                    }
                });

                // 2. 載入設定
                self.settingsManager.loadSettings()
                    .then(function(settings) {
                        console.log('📋 設定載入完成:', settings);

                        // 3. 初始化 UI 管理器
                        self.uiManager = new window.MCPFeedback.UIManager({
                            layoutMode: settings.layoutMode,
                            onTabChange: function(tabName) {
                                self.handleTabChange(tabName);
                            },
                            onLayoutModeChange: function(layoutMode) {
                                self.handleLayoutModeChange(layoutMode);
                            }
                        });

                        // 4. 初始化分頁管理器
                        if (window.MCPFeedback.TabManager) {
                            self.tabManager = new window.MCPFeedback.TabManager();
                        }

                        // 5. 初始化連線監控器
                        self.connectionMonitor = new window.MCPFeedback.ConnectionMonitor({
                            onStatusChange: function(status, message) {
                                console.log('🔍 連線狀態變更:', status, message);
                            },
                            onQualityChange: function(quality, latency) {
                                console.log('🔍 連線品質變更:', quality, latency + 'ms');
                            }
                        });

                        // 6. 初始化會話管理器
                        self.sessionManager = new window.MCPFeedback.SessionManager({
                            settingsManager: self.settingsManager,
                            onSessionChange: function(sessionData) {
                                console.log('📋 會話變更:', sessionData);
                            },
                            onSessionSelect: function(sessionId) {
                                console.log('📋 會話選擇:', sessionId);
                            }
                        });

                        // 7. 初始化 WebSocket 管理器
                        self.webSocketManager = new window.MCPFeedback.WebSocketManager({
                            tabManager: self.tabManager,
                            connectionMonitor: self.connectionMonitor,
                            onOpen: function() {
                                self.handleWebSocketOpen();
                            },
                            onMessage: function(data) {
                                self.handleWebSocketMessage(data);
                            },
                            onClose: function(event) {
                                self.handleWebSocketClose(event);
                            },
                            onConnectionStatusChange: function(status, text) {
                                self.uiManager.updateConnectionStatus(status, text);
                                if (self.connectionMonitor) {
                                    self.connectionMonitor.updateConnectionStatus(status, text);
                                }
                            }
                        });

                        // 8. 初始化圖片處理器
                        self.imageHandler = new window.MCPFeedback.ImageHandler({
                            imageSizeLimit: settings.imageSizeLimit,
                            enableBase64Detail: settings.enableBase64Detail,
                            layoutMode: settings.layoutMode,
                            onSettingsChange: function() {
                                self.saveImageSettings();
                            }
                        });

                        // 9. 初始化提示詞管理器
                        self.initializePromptManagers();

                        // 10. 初始化音效管理器
                        self.initializeAudioManagers();

                        // 11. 初始化通知管理器
                        self.initializeNotificationManager();

                        // 12. 初始化 Textarea 高度管理器
                        self.initializeTextareaHeightManager();

                        // 13. 應用設定到 UI
                        self.settingsManager.applyToUI();

                        // 14. 初始化各個管理器
                        self.uiManager.initTabs();
                        self.imageHandler.init();

                        // 15. 播放啟動音效
                        setTimeout(function() {
                            if (self.audioManager) {
                                self.audioManager.playStartupNotification();
                            }
                        }, 800);

                        // 16. 建立 WebSocket 連接
                        self.webSocketManager.connect();

                        resolve();
                    })
                    .catch(reject);
            } catch (error) {
                reject(error);
            }
        });
    };

    /**
     * 設置事件監聽器
     */
    FeedbackApp.prototype.setupEventListeners = function() {
        const self = this;

        return new Promise(function(resolve) {
            // 提交按鈕事件
            const submitBtn = window.MCPFeedback.Utils.safeQuerySelector('#submitBtn');
            if (submitBtn) {
                submitBtn.addEventListener('click', function() {
                    self.submitFeedback();
                });
            }

            // 清空输入按钮
            var clearInputBtn = window.MCPFeedback.Utils.safeQuerySelector('#clearInputBtn');
            if (clearInputBtn) {
                clearInputBtn.addEventListener('click', function() {
                    self.clearFeedback();
                });
            }

            // 队列面板事件
            var clearQueueBtn = window.MCPFeedback.Utils.safeQuerySelector('#clearQueueBtn');
            if (clearQueueBtn) {
                clearQueueBtn.addEventListener('click', function() {
                    self.clearQueue();
                });
            }
            var queueToggleBtn = window.MCPFeedback.Utils.safeQuerySelector('#queueToggleBtn');
            if (queueToggleBtn) {
                queueToggleBtn.addEventListener('click', function() {
                    self.toggleQueuePanel();
                });
            }
            self.refreshQueueStatus();
            self.syncSubmitButtonWithServer();

            // 历史面板事件
            var historyToggleBtn = window.MCPFeedback.Utils.safeQuerySelector('#historyToggleBtn');
            if (historyToggleBtn) {
                historyToggleBtn.addEventListener('click', function() {
                    self.toggleHistoryPanel();
                });
            }
            var historyTabAI = window.MCPFeedback.Utils.safeQuerySelector('#historyTabAI');
            var historyTabUser = window.MCPFeedback.Utils.safeQuerySelector('#historyTabUser');
            if (historyTabAI) {
                historyTabAI.addEventListener('click', function() {
                    self.renderHistoryPanel('ai');
                });
            }
            if (historyTabUser) {
                historyTabUser.addEventListener('click', function() {
                    self.renderHistoryPanel('user');
                });
            }

            // 命令執行事件
            const runCommandBtn = window.MCPFeedback.Utils.safeQuerySelector('#runCommandBtn');
            if (runCommandBtn) {
                runCommandBtn.addEventListener('click', function() {
                    self.runCommand();
                });
            }

            const commandInput = window.MCPFeedback.Utils.safeQuerySelector('#commandInput');
            if (commandInput) {
                commandInput.addEventListener('keydown', function(e) {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        self.runCommand();
                    }
                });
            }

            // 複製用戶內容按鈕
            const copyUserFeedback = window.MCPFeedback.Utils.safeQuerySelector('#copyUserFeedback');
            if (copyUserFeedback) {
                copyUserFeedback.addEventListener('click', function(e) {
                    e.preventDefault();
                    self.copyUserFeedback();
                });
            }

            // 回饋輸入框草稿自動保存
            var feedbackTextarea = Utils.safeQuerySelector('#combinedFeedbackText');
            if (feedbackTextarea) {
                feedbackTextarea.addEventListener('input', function() {
                    self.saveFeedbackDraft();
                });
            }

            // 快捷鍵
            document.addEventListener('keydown', function(e) {
                if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
                    e.preventDefault();
                    self.submitFeedback();
                }
                if ((e.ctrlKey || e.metaKey) && e.key === 'i') {
                    e.preventDefault();
                    self.focusInput();
                }
            });

            self.setupAutoCommandEvents();
            self.settingsManager.setupEventListeners();

            console.log('✅ 事件監聽器設置完成');
            resolve();
        });
    };

    /**
     * 設置清理處理器
     */
    FeedbackApp.prototype.setupCleanupHandlers = function() {
        const self = this;
        return new Promise(function(resolve) {
            window.addEventListener('beforeunload', function() {
                self.cleanup();
            });
            console.log('✅ 清理處理器設置完成');
            resolve();
        });
    };

    /**
     * 處理設定變更
     */
    FeedbackApp.prototype.handleSettingsChange = function(settings) {
        if (this.imageHandler) {
            this.imageHandler.updateSettings(settings);
        }
        if (this.uiManager && settings.layoutMode) {
            this.uiManager.applyLayoutMode(settings.layoutMode);
        }
    };

    /**
     * 處理語言變更
     */
    FeedbackApp.prototype.handleLanguageChange = function(language) {
        if (this.uiManager) {
            this.uiManager.updateStatusIndicator();
        }
    };

    /**
     * 處理頁籤變更
     */
    FeedbackApp.prototype.handleTabChange = function(tabName) {
        if (this.imageHandler) {
            const layoutMode = this.settingsManager.get('layoutMode');
            this.imageHandler.reinitialize(layoutMode);
        }
    };

    /**
     * 處理佈局模式變更
     */
    FeedbackApp.prototype.handleLayoutModeChange = function(layoutMode) {
        if (this.imageHandler) {
            this.imageHandler.reinitialize(layoutMode);
        }
    };

    /**
     * 保存圖片設定
     */
    FeedbackApp.prototype.saveImageSettings = function() {
        if (this.imageHandler && this.settingsManager) {
            this.settingsManager.setMultiple({
                imageSizeLimit: this.imageHandler.imageSizeLimit,
                enableBase64Detail: this.imageHandler.enableBase64Detail
            });
        }
    };

    /**
     * 初始化提示詞管理器
     */
    FeedbackApp.prototype.initializePromptManagers = function() {
        try {
            if (!window.MCPFeedback.Prompt) return;
            this.promptManager = new window.MCPFeedback.Prompt.PromptManager({
                settingsManager: this.settingsManager
            });
            this.promptManager.init();
            this.promptModal = new window.MCPFeedback.Prompt.PromptModal();
            this.promptSettingsUI = new window.MCPFeedback.Prompt.PromptSettingsUI({
                promptManager: this.promptManager,
                promptModal: this.promptModal,
                settingsManager: this.settingsManager
            });
            this.promptSettingsUI.init('#promptManagementContainer');
            this.promptInputButtons = new window.MCPFeedback.Prompt.PromptInputButtons({
                promptManager: this.promptManager,
                promptModal: this.promptModal
            });
            this.promptInputButtons.init(['#combinedFeedbackText']);
        } catch (error) {
            console.error('❌ 提示詞管理器初始化失敗:', error);
        }
    };

    /**
     * 初始化音效管理器
     */
    FeedbackApp.prototype.initializeAudioManagers = function() {
        try {
            if (!window.MCPFeedback.AudioManager) return;
            this.audioManager = new window.MCPFeedback.AudioManager({
                settingsManager: this.settingsManager
            });
            this.audioManager.initialize();
            this.audioSettingsUI = new window.MCPFeedback.AudioSettingsUI({
                container: document.querySelector('#audioManagementContainer'),
                audioManager: this.audioManager,
                t: window.i18nManager ? window.i18nManager.t.bind(window.i18nManager) : function(k, d) { return d || k; }
            });
            this.audioSettingsUI.initialize();
        } catch (error) {
            console.error('❌ 音效管理器初始化失敗:', error);
        }
    };

    /**
     * 初始化通知管理器
     */
    FeedbackApp.prototype.initializeNotificationManager = function() {
        try {
            if (!window.MCPFeedback.NotificationManager) return;
            this.notificationManager = new window.MCPFeedback.NotificationManager({
                t: window.i18nManager ? window.i18nManager.t.bind(window.i18nManager) : function(k, d) { return d || k; }
            });
            this.notificationManager.initialize();
            if (window.MCPFeedback.NotificationSettings) {
                const container = document.querySelector('#notificationSettingsContainer');
                if (container) {
                    this.notificationSettings = new window.MCPFeedback.NotificationSettings({
                        container: container,
                        notificationManager: this.notificationManager,
                        t: window.i18nManager ? window.i18nManager.t.bind(window.i18nManager) : function(k, d) { return d || k; }
                    });
                    this.notificationSettings.initialize();
                }
            }
        } catch (error) {
            console.error('❌ 通知管理器初始化失敗:', error);
        }
    };

    /**
     * 初始化 Textarea 高度管理器
     */
    FeedbackApp.prototype.initializeTextareaHeightManager = function() {
        try {
            if (!window.MCPFeedback.TextareaHeightManager) return;
            this.textareaHeightManager = new window.MCPFeedback.TextareaHeightManager({
                settingsManager: this.settingsManager
            });
            this.textareaHeightManager.initialize();
            this.textareaHeightManager.registerTextarea('combinedFeedbackText', 'combinedFeedbackTextHeight');
        } catch (error) {
            console.error('❌ Textarea 高度管理器初始化失敗:', error);
        }
    };

    /**
     * 處理 WebSocket 開啟
     */
    FeedbackApp.prototype.handleWebSocketOpen = function() {
        if (this.pendingSubmission) {
            this.submitFeedbackInternal(this.pendingSubmission);
            this.pendingSubmission = null;
        }
        this.syncSubmitButtonWithServer();
    };

    /**
     * 處理 WebSocket 訊息
     */
    FeedbackApp.prototype._originalHandleWebSocketMessage = function(data) {
        switch (data.type) {
            case 'command_output':
                this.appendCommandOutput(data.output);
                break;
            case 'command_complete':
                this.appendCommandOutput('\n[命令完成，退出碼: ' + data.exit_code + ']\n');
                this.enableCommandInput();
                break;
            case 'command_error':
                this.appendCommandOutput('\n[錯誤: ' + data.error + ']\n');
                this.enableCommandInput();
                break;
            case 'feedback_received':
                this.handleFeedbackReceived(data);
                break;
            case 'status_update':
                this._originalHandleStatusUpdate(data.status_info);
                break;
            case 'session_updated':
                if (data.messageCode && window.i18nManager) {
                    const message = window.i18nManager.t(data.messageCode);
                    Utils.showMessage(message, Utils.CONSTANTS.MESSAGE_SUCCESS);
                }
                this._originalHandleSessionUpdated(data);
                break;
            case 'desktop_close_request':
                this.handleDesktopCloseRequest(data);
                break;
            case 'notification':
                if (data.code === 'session.feedbackSubmitted' || data.code === 'FEEDBACK_SUBMITTED' || data.code === 201) {
                    this.handleFeedbackReceived(data);
                }
                break;
            case 'queue_updated':
                this.updateQueueBadge(data.size);
                this.refreshQueueStatus();
                break;
            case 'queue_item_consumed':
                this.updateQueueBadge(data.remaining);
                this.refreshQueueStatus();
                Utils.showMessage('队列中的反馈已发送给 AI（剩余 ' + data.remaining + ' 条）', Utils.CONSTANTS.MESSAGE_SUCCESS);
                break;
        }
    };

    FeedbackApp.prototype.handleWebSocketMessage = function(data) {
        if (data.type === 'command_output' || data.type === 'command_complete' || data.type === 'command_error') {
            this._originalHandleWebSocketMessage(data);
        } else {
            this._debouncedHandleWebSocketMessage(data);
        }
    };

    /**
     * 處理 WebSocket 關閉
     */
    FeedbackApp.prototype.handleWebSocketClose = function(event) {
        if (this.uiManager && this.uiManager.getFeedbackState() === Utils.CONSTANTS.FEEDBACK_PROCESSING) {
            this.uiManager.setFeedbackState(Utils.CONSTANTS.FEEDBACK_WAITING);
        }
        this.updateSubmitButtonState(false);
    };

    /**
     * 處理回饋接收
     */
    FeedbackApp.prototype.handleFeedbackReceived = function(data) {
        this.uiManager.setFeedbackState(Utils.CONSTANTS.FEEDBACK_SUBMITTED);
        this.uiManager.setLastSubmissionTime(Date.now());
        const message = data.messageCode && window.i18nManager ? 
            window.i18nManager.t(data.messageCode, data.params) : 
            (data.message || (window.i18nManager ? window.i18nManager.t('feedback.submitSuccess') : '回饋提交成功！'));
        Utils.showMessage(message, Utils.CONSTANTS.MESSAGE_SUCCESS);
        this.updateSummaryStatus(window.i18nManager ? window.i18nManager.t('feedback.submittedWaiting') : '已送出反饋，等待下次 MCP 調用...');
        this.updateSubmitButtonState(false);
        this.executeAutoCommandOnFeedbackSubmit();
        this.refreshSessionList();
    };

    FeedbackApp.prototype.refreshSessionList = function() {
        if (this.sessionManager && this.sessionManager.dataManager) {
            this.sessionManager.dataManager.loadFromServer();
        }
    };

    FeedbackApp.prototype.handleDesktopCloseRequest = function(data) {
        const closeMessage = data.message || '正在關閉桌面應用程式...';
        Utils.showMessage(closeMessage, Utils.CONSTANTS.MESSAGE_INFO);
        if (window.__TAURI__) {
            try { window.__TAURI__.window.getCurrent().close(); } catch (e) { window.close(); }
        } else {
            window.close();
        }
    };

    FeedbackApp.prototype._originalHandleSessionUpdated = function(data) {
        if (data.action === 'new_session_created' || data.type === 'new_session_created') {
            if (this.audioManager) this.audioManager.playNotification();
            this.executeAutoCommandOnNewSession();
            if (this.notificationManager && data.session_info) {
                this.notificationManager.notifyNewSession(data.session_info.session_id, data.session_info.project_directory || '未知專案');
            }
            const msg = data.message || (window.i18nManager ? window.i18nManager.t('session.created') : 'New MCP session created');
            Utils.showMessage(msg, Utils.CONSTANTS.MESSAGE_SUCCESS);
            const self = this;
            setTimeout(function() {
                if (data.session_info) self.currentSessionId = data.session_info.session_id;
                self.saveFeedbackDraft();
                self.refreshPageContent();
                if (self.uiManager) self.uiManager.setFeedbackState(Utils.CONSTANTS.FEEDBACK_WAITING, self.currentSessionId);
                self.restoreFeedbackDraft();
            }, 500);
            return;
        }
        if (this.audioManager) this.audioManager.playNotification();
        Utils.showMessage(data.message || '會話已更新', Utils.CONSTANTS.MESSAGE_SUCCESS);
        if (data.session_info) {
            const newSessionId = data.session_info.session_id;
            if (this.currentSessionId && this.sessionManager && this.currentSessionId !== newSessionId) {
                const currentData = this.sessionManager.getCurrentSessionData();
                if (currentData) {
                    const now = Date.now() / 1000;
                    const duration = currentData.created_at ? Math.max(1, Math.round(now - (currentData.created_at > 1e12 ? currentData.created_at/1000 : currentData.created_at))) : 300;
                    this.sessionManager.dataManager.addSessionToHistory({
                        session_id: this.currentSessionId,
                        status: 'completed',
                        created_at: currentData.created_at || (now - duration),
                        completed_at: now,
                        duration: duration,
                        project_directory: currentData.project_directory,
                        summary: currentData.summary
                    });
                }
            }
            this.currentSessionId = newSessionId;
            if (this.sessionManager) this.sessionManager.updateCurrentSession(data.session_info);
            const currentState = this.uiManager.getFeedbackState();
            if (currentState !== Utils.CONSTANTS.FEEDBACK_SUBMITTED) {
                this.uiManager.setFeedbackState(Utils.CONSTANTS.FEEDBACK_WAITING, newSessionId);
            }
            this.refreshPageContent();
        }
    };

    FeedbackApp.prototype.handleSessionUpdated = function(data) {
        this._debouncedHandleSessionUpdated(data);
    };

    FeedbackApp.prototype._originalHandleStatusUpdate = function(statusInfo) {
        if (this.sessionManager) this.sessionManager.updateStatusInfo(statusInfo);
        if (statusInfo.session_id) this.currentSessionId = statusInfo.session_id;
        this.refreshSessionList();
        const msgMap = {
            'feedback_submitted': 'feedback.submittedWaiting',
            'waiting': 'feedback.waitingForUser',
            'completed': 'feedback.completed'
        };
        const key = msgMap[statusInfo.status];
        if (key) this.updateSummaryStatus(window.i18nManager ? window.i18nManager.t(key) : statusInfo.status);
    };

    FeedbackApp.prototype.handleStatusUpdate = function(statusInfo) {
        this._debouncedHandleStatusUpdate(statusInfo);
    };

    FeedbackApp.prototype.submitFeedback = function() {
        if (!this.webSocketManager || !this.webSocketManager.isReady()) {
            this.enqueueFeedback();
            return;
        }
        var self = this;
        fetch('/api/can-submit')
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.can_submit) {
                var feedbackData = self.collectFeedbackData();
                if (feedbackData) self.submitFeedbackInternal(feedbackData);
            } else {
                self.enqueueFeedback();
            }
        })
        .catch(function() {
            self.enqueueFeedback();
        });
    };

    FeedbackApp.prototype.collectFeedbackData = function() {
        const feedbackInput = Utils.safeQuerySelector('#combinedFeedbackText');
        const feedback = feedbackInput ? feedbackInput.value.trim() : '';
        const images = this.imageHandler ? this.imageHandler.getImages() : [];
        if (!feedback && images.length === 0) {
            Utils.showMessage(window.i18nManager ? window.i18nManager.t('feedback.provideTextOrImage') : '請提供回饋', Utils.CONSTANTS.MESSAGE_WARNING);
            return null;
        }
        return {
            feedback: feedback,
            images: images,
            settings: {
                image_size_limit: this.imageHandler ? this.imageHandler.imageSizeLimit : 0,
                enable_base64_detail: this.imageHandler ? this.imageHandler.enableBase64Detail : false
            }
        };
    };

    FeedbackApp.prototype.submitFeedbackInternal = function(feedbackData) {
        this.saveUserInputToHistory(feedbackData.feedback);
        this.recordUserMessage(feedbackData);
        if (this.uiManager) this.uiManager.setFeedbackState(Utils.CONSTANTS.FEEDBACK_PROCESSING);
        const success = this.webSocketManager.send({
            type: 'submit_feedback',
            feedback: feedbackData.feedback,
            images: feedbackData.images,
            settings: feedbackData.settings
        });
        if (success) {
            if (this.uiManager) this.uiManager.resetFeedbackForm(false);
            if (this.imageHandler) this.imageHandler.clearImages();
            this.clearFeedbackDraft();
        } else {
            Utils.showMessage(window.i18nManager ? window.i18nManager.t('feedback.sendFailed') : '發送失敗', Utils.CONSTANTS.MESSAGE_ERROR);
            if (this.uiManager) this.uiManager.setFeedbackState(Utils.CONSTANTS.FEEDBACK_WAITING);
        }
    };

    FeedbackApp.prototype.recordUserMessage = function(feedbackData) {
        if (!this.sessionManager || !this.sessionManager.dataManager) return;
        this.sessionManager.dataManager.addUserMessage({
            content: feedbackData.feedback || '',
            images: feedbackData.images || [],
            submission_method: 'manual'
        });
    };

    FeedbackApp.prototype.clearFeedback = function() {
        if (this.uiManager) this.uiManager.resetFeedbackForm(true);
        if (this.imageHandler) this.imageHandler.clearImages();
        this.pendingSubmission = null;
        this.clearFeedbackDraft();
    };

    // ===== 队列功能 =====

    FeedbackApp.prototype.updateSubmitButtonState = function(canSubmit) {
        var btn = document.getElementById('submitBtn');
        if (!btn) return;
        btn.style.cssText = '';
        btn.disabled = false;
        if (canSubmit) {
            btn.textContent = '✅ 提交回饋';
            btn.className = 'btn btn-success combined-submit-btn';
            btn.title = '立即提交给 AI';
        } else {
            btn.textContent = '📥 提交到队列';
            btn.className = 'btn combined-submit-btn';
            btn.style.background = 'transparent';
            btn.style.border = '1.5px solid #3b82f6';
            btn.style.color = '#60a5fa';
            btn.title = 'AI 未在等待，将加入队列';
        }
        var feedbackInput = document.getElementById('combinedFeedbackText');
        if (feedbackInput) feedbackInput.disabled = false;
    };

    FeedbackApp.prototype.syncSubmitButtonWithServer = function() {
        var self = this;
        fetch('/api/can-submit')
        .then(function(r) { return r.json(); })
        .then(function(data) {
            self.updateSubmitButtonState(data.can_submit);
        })
        .catch(function() {
            self.updateSubmitButtonState(false);
        });
    };

    FeedbackApp.prototype.enqueueFeedback = function() {
        var feedbackData = this.collectFeedbackData();
        if (!feedbackData) return;
        this.saveUserInputToHistory(feedbackData.feedback);
        var self = this;
        fetch('/api/queue-feedback', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(feedbackData)
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.status === 'success') {
                Utils.showMessage('已加入队列（共 ' + data.queue_size + ' 条）', Utils.CONSTANTS.MESSAGE_SUCCESS);
                var input = document.getElementById('combinedFeedbackText');
                if (input) { input.value = ''; input.disabled = false; }
                if (self.imageHandler) self.imageHandler.clearImages();
                self.clearFeedbackDraft();
                self.updateQueueBadge(data.queue_size);
            } else {
                Utils.showMessage(data.error || '入队失败', Utils.CONSTANTS.MESSAGE_ERROR);
            }
        })
        .catch(function(err) {
            Utils.showMessage('入队请求失败: ' + err.message, Utils.CONSTANTS.MESSAGE_ERROR);
        });
    };

    FeedbackApp.prototype.refreshQueueStatus = function() {
        var self = this;
        fetch('/api/queue-status')
        .then(function(r) { return r.json(); })
        .then(function(data) {
            self.updateQueueBadge(data.size);
            self.renderQueueList(data.items || []);
        })
        .catch(function() {});
    };

    FeedbackApp.prototype.updateQueueBadge = function(size) {
        var badge = document.getElementById('queueBadge');
        if (!badge) return;
        if (size > 0) {
            badge.textContent = size;
            badge.style.display = 'inline';
        } else {
            badge.style.display = 'none';
        }
    };

    FeedbackApp.prototype.toggleQueuePanel = function() {
        var panel = document.getElementById('queuePanel');
        if (!panel) return;
        var visible = panel.style.display !== 'none';
        if (!visible) {
            var historyPanel = document.getElementById('historyPanel');
            if (historyPanel) historyPanel.style.display = 'none';
            var historyBtn = document.getElementById('historyToggleBtn');
            if (historyBtn) { historyBtn.style.borderColor = '#4b5563'; historyBtn.style.color = '#94a3b8'; }
        }
        panel.style.display = visible ? 'none' : 'block';
        var toggleBtn = document.getElementById('queueToggleBtn');
        if (toggleBtn) {
            toggleBtn.style.borderColor = visible ? '#4b5563' : '#3b82f6';
            toggleBtn.style.color = visible ? '#94a3b8' : '#60a5fa';
        }
        if (!visible) this.refreshQueueStatus();
    };

    FeedbackApp.prototype.renderQueueList = function(items) {
        var list = document.getElementById('queueList');
        var empty = document.getElementById('queueEmpty');
        if (!list || !empty) return;
        if (items.length === 0) {
            list.innerHTML = '';
            empty.style.display = 'block';
            return;
        }
        empty.style.display = 'none';
        var self = this;
        var html = '';
        items.forEach(function(item, idx) {
            var time = new Date(item.queued_at * 1000).toLocaleTimeString();
            var preview = item.feedback_preview || '(空)';
            var imgTag = item.has_images ? ' 🖼' : '';
            html += '<div style="display:flex; justify-content:space-between; align-items:center; padding:6px 8px; background:#0f172a; border-radius:4px; margin-bottom:4px; font-size:0.85em;">'
                + '<div style="flex:1; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; color:#cbd5e1;">'
                + '<span style="color:#64748b; margin-right:6px;">#' + (idx+1) + '</span>'
                + self.escapeHtml(preview) + imgTag
                + '</div>'
                + '<div style="display:flex; align-items:center; gap:6px; margin-left:8px; flex-shrink:0;">'
                + '<span style="color:#64748b; font-size:0.8em;">' + time + '</span>'
                + '<button onclick="window.MCPFeedback.app.removeQueueItem(\'' + item.id + '\')" style="background:none; border:none; color:#ef4444; cursor:pointer; font-size:1em; padding:0 2px;">×</button>'
                + '</div></div>';
        });
        list.innerHTML = html;
    };

    FeedbackApp.prototype.escapeHtml = function(s) {
        var div = document.createElement('div');
        div.textContent = s;
        return div.innerHTML;
    };

    FeedbackApp.prototype.removeQueueItem = function(itemId) {
        var self = this;
        fetch('/api/queue-item/' + itemId, { method: 'DELETE' })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.status === 'success') {
                self.updateQueueBadge(data.queue_size);
                self.refreshQueueStatus();
            }
        })
        .catch(function() {});
    };

    FeedbackApp.prototype.clearQueue = function() {
        var self = this;
        fetch('/api/queue', { method: 'DELETE' })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.status === 'success') {
                self.updateQueueBadge(0);
                self.refreshQueueStatus();
                Utils.showMessage('队列已清空', Utils.CONSTANTS.MESSAGE_SUCCESS);
            }
        })
        .catch(function() {});
    };

    FeedbackApp.prototype.focusInput = function() {
        const targetInput = Utils.safeQuerySelector('#combinedFeedbackText');
        if (this.uiManager && this.uiManager.getCurrentTab() !== 'combined') this.uiManager.switchTab('combined');
        if (targetInput) {
            targetInput.focus();
            targetInput.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    };

    FeedbackApp.prototype.runCommand = function() {
        const commandInput = Utils.safeQuerySelector('#commandInput');
        const command = commandInput ? commandInput.value.trim() : '';
        if (!command) return;
        if (!this.webSocketManager || !this.webSocketManager.isConnected) {
            this.appendCommandOutput('❌ WebSocket 未連接\n');
            return;
        }
        this.appendCommandOutput('$ ' + command + '\n');
        const success = this.webSocketManager.send({ type: 'run_command', command: command });
        if (success) commandInput.value = '';
    };

    FeedbackApp.prototype.appendCommandOutput = function(output) {
        const commandOutput = Utils.safeQuerySelector('#commandOutput');
        if (commandOutput) {
            commandOutput.textContent += output;
            commandOutput.scrollTop = commandOutput.scrollHeight;
        }
    };

    FeedbackApp.prototype.enableCommandInput = function() {
        const commandInput = Utils.safeQuerySelector('#commandInput');
        const runCommandBtn = Utils.safeQuerySelector('#runCommandBtn');
        if (commandInput) commandInput.disabled = false;
        if (runCommandBtn) { runCommandBtn.disabled = false; runCommandBtn.textContent = '▶️ 執行'; }
    };

    FeedbackApp.prototype.executeAutoCommandOnNewSession = function() {
        if (!this.settingsManager) return;
        const settings = this.settingsManager.currentSettings;
        if (!settings.autoCommandEnabled || !settings.commandOnNewSession) return;
        const command = settings.commandOnNewSession.trim();
        if (command && this.webSocketManager && this.webSocketManager.isConnected) {
            this.appendCommandOutput('🆕 [自動執行] $ ' + command + '\n');
            this.webSocketManager.send({ type: 'run_command', command: command });
        }
    };

    FeedbackApp.prototype.executeAutoCommandOnFeedbackSubmit = function() {
        if (!this.settingsManager) return;
        const settings = this.settingsManager.currentSettings;
        if (!settings.autoCommandEnabled || !settings.commandOnFeedbackSubmit) return;
        const command = settings.commandOnFeedbackSubmit.trim();
        if (command && this.webSocketManager && this.webSocketManager.isConnected) {
            this.appendCommandOutput('✅ [自動執行] $ ' + command + '\n');
            this.webSocketManager.send({ type: 'run_command', command: command });
        }
    };

    FeedbackApp.prototype.updateSummaryStatus = function(message) {
        const summaryElements = document.querySelectorAll('.ai-summary-content');
        summaryElements.forEach(function(el) {
            el.innerHTML = '<div style="padding: 16px; background: var(--success-color); color: white; border-radius: 6px; text-align: center;">✅ ' + message + '</div>';
        });
    };

    FeedbackApp.prototype.setupAutoCommandEvents = function() {
        const self = this;
        const autoCommandEnabled = Utils.safeQuerySelector('#autoCommandEnabled');
        if (autoCommandEnabled && this.settingsManager) {
            autoCommandEnabled.checked = this.settingsManager.currentSettings.autoCommandEnabled;
            autoCommandEnabled.addEventListener('change', function() {
                self.settingsManager.saveSettings({ autoCommandEnabled: autoCommandEnabled.checked });
            });
        }
        const commandOnNewSession = Utils.safeQuerySelector('#commandOnNewSession');
        if (commandOnNewSession && this.settingsManager) {
            commandOnNewSession.value = this.settingsManager.currentSettings.commandOnNewSession || '';
            commandOnNewSession.addEventListener('change', function() {
                self.settingsManager.saveSettings({ commandOnNewSession: commandOnNewSession.value });
            });
        }
        const commandOnFeedbackSubmit = Utils.safeQuerySelector('#commandOnFeedbackSubmit');
        if (commandOnFeedbackSubmit && this.settingsManager) {
            commandOnFeedbackSubmit.value = this.settingsManager.currentSettings.commandOnFeedbackSubmit || '';
            commandOnFeedbackSubmit.addEventListener('change', function() {
                self.settingsManager.saveSettings({ commandOnFeedbackSubmit: commandOnFeedbackSubmit.value });
            });
        }
    };

    FeedbackApp.prototype.refreshPageContent = function() {
        const self = this;
        fetch('/api/current-session')
            .then(res => res.ok ? res.json() : Promise.reject())
            .then(data => {
                if (self.uiManager) {
                    self.uiManager.updateAISummaryContent(data.summary);
                    const currentState = self.uiManager.getFeedbackState();
                    if (currentState !== Utils.CONSTANTS.FEEDBACK_SUBMITTED) {
                        self.uiManager.setFeedbackState(Utils.CONSTANTS.FEEDBACK_WAITING, data.session_id);
                    }
                }
                if (data.project_directory) {
                    const projectName = data.project_directory.split(/[/\\]/).pop();
                    document.title = 'MCP Feedback - ' + projectName;
                }
            })
            .catch(err => console.error('❌ 局部刷新失敗:', err));
    };

    FeedbackApp.prototype.cleanup = function() {
        if (this.webSocketManager) this.webSocketManager.close();
    };

    FeedbackApp.DRAFT_STORAGE_KEY = 'mcp_feedback_draft_content';

    FeedbackApp.prototype.saveFeedbackDraft = function() {
        var feedbackInput = Utils.safeQuerySelector('#combinedFeedbackText');
        if (feedbackInput) {
            try {
                localStorage.setItem(FeedbackApp.DRAFT_STORAGE_KEY, feedbackInput.value);
            } catch (e) {
                console.warn('⚠️ 無法保存草稿到 localStorage:', e);
            }
        }
    };

    FeedbackApp.prototype.restoreFeedbackDraft = function() {
        var feedbackInput = Utils.safeQuerySelector('#combinedFeedbackText');
        if (feedbackInput) {
            try {
                var savedDraft = localStorage.getItem(FeedbackApp.DRAFT_STORAGE_KEY);
                if (savedDraft) {
                    feedbackInput.value = savedDraft;
                    console.log('📝 已從瀏覽器恢復草稿內容，長度:', savedDraft.length);
                }
            } catch (e) {
                console.warn('⚠️ 無法從 localStorage 恢復草稿:', e);
            }
        }
    };

    FeedbackApp.prototype.clearFeedbackDraft = function() {
        try {
            localStorage.removeItem(FeedbackApp.DRAFT_STORAGE_KEY);
        } catch (e) {
            console.warn('⚠️ 無法清除 localStorage 草稿:', e);
        }
    };

    // ===== 历史记录功能 =====

    FeedbackApp.HISTORY_MAX = 10;

    FeedbackApp.prototype.saveToHistory = function(tab, content) {
        if (!content || !content.trim()) return;
        fetch('/api/history', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ tab: tab, content: content.trim() })
        }).catch(function(e) {
            console.warn('历史记录保存失败:', e);
        });
    };

    FeedbackApp.prototype.getHistory = function(tab, callback) {
        fetch('/api/history?tab=' + encodeURIComponent(tab))
        .then(function(r) { return r.json(); })
        .then(function(data) { callback(data.items || []); })
        .catch(function() { callback([]); });
    };

    FeedbackApp.prototype.saveAISummaryToHistory = function(summary) {
        this.saveToHistory('ai', summary);
    };

    FeedbackApp.prototype.saveUserInputToHistory = function(text) {
        this.saveToHistory('user', text);
    };

    FeedbackApp.prototype.toggleHistoryPanel = function() {
        var panel = document.getElementById('historyPanel');
        if (!panel) return;
        var visible = panel.style.display !== 'none';
        if (!visible) {
            var queuePanel = document.getElementById('queuePanel');
            if (queuePanel) queuePanel.style.display = 'none';
            var queueBtn = document.getElementById('queueToggleBtn');
            if (queueBtn) { queueBtn.style.borderColor = '#4b5563'; queueBtn.style.color = '#94a3b8'; }
        }
        panel.style.display = visible ? 'none' : 'block';
        var toggleBtn = document.getElementById('historyToggleBtn');
        if (toggleBtn) {
            toggleBtn.style.borderColor = visible ? '#4b5563' : '#3b82f6';
            toggleBtn.style.color = visible ? '#94a3b8' : '#60a5fa';
        }
        if (!visible) this.renderHistoryPanel('ai');
    };

    FeedbackApp.prototype.extractFirstHeading = function(markdown) {
        var match = markdown.match(/^#{1,3}\s+(.+)/m);
        return match ? match[1].replace(/[*_`#]/g, '').trim() : '';
    };

    FeedbackApp.prototype.renderHistoryPanel = function(tab) {
        var aiTab = document.getElementById('historyTabAI');
        var userTab = document.getElementById('historyTabUser');
        var list = document.getElementById('historyList');
        if (!aiTab || !userTab || !list) return;

        var isAI = tab === 'ai';
        aiTab.style.borderBottom = isAI ? '2px solid #3b82f6' : '2px solid transparent';
        aiTab.style.color = isAI ? '#60a5fa' : '#94a3b8';
        userTab.style.borderBottom = !isAI ? '2px solid #3b82f6' : '2px solid transparent';
        userTab.style.color = !isAI ? '#60a5fa' : '#94a3b8';

        list.innerHTML = '<div style="color:#6b7280; text-align:center; padding:16px; font-size:0.85em;">加载中...</div>';

        var self = this;
        this.getHistory(tab, function(items) {
            var countEl = document.getElementById('historyCount');
            if (countEl) countEl.textContent = items.length + ' / ' + FeedbackApp.HISTORY_MAX;

            if (items.length === 0) {
                list.innerHTML = '<div style="color:#6b7280; text-align:center; padding:24px; font-size:0.85em;">'
                    + (isAI ? '暂无 AI 工作摘要记录' : '暂无用户输入记录') + '</div>';
                return;
            }
            self._renderHistoryItems(list, items, tab, isAI);
        });
    };

    FeedbackApp.prototype._renderHistoryItems = function(list, items, tab, isAI) {
        var self = this;
        var html = '';
        items.forEach(function(item, idx) {
            var d = new Date(item.time);
            var timeStr = d.toLocaleDateString(undefined, {month:'short', day:'numeric'})
                + ' ' + d.toLocaleTimeString(undefined, {hour:'2-digit', minute:'2-digit'});

            html += '<div class="history-item" data-idx="' + idx + '" data-tab="' + tab + '" style="padding:10px 12px; background:#0f172a; border:1px solid transparent; border-radius:8px; margin-bottom:6px; cursor:pointer; transition:all 0.15s;">';

            if (isAI) {
                var heading = self.extractFirstHeading(item.content);
                if (heading) {
                    html += '<div style="font-weight:600; color:#e2e8f0; font-size:0.88em; margin-bottom:4px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">' + self.escapeHtml(heading) + '</div>';
                }
                var bodyPreview = item.content.replace(/^#{1,6}\s+.+\n?/m, '').trim().substring(0, 120).replace(/\n/g, ' ');
                if (bodyPreview.length >= 120) bodyPreview += '…';
                html += '<div style="display:flex; justify-content:space-between; align-items:flex-end; gap:8px;">';
                html += '<div class="history-md-preview" style="flex:1; overflow:hidden; color:#94a3b8; font-size:0.82em; line-height:1.4; max-height:2.8em; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical;">' + self.escapeHtml(bodyPreview) + '</div>';
                html += '<span style="color:#475569; font-size:0.72em; white-space:nowrap; flex-shrink:0;">' + timeStr + '</span>';
                html += '</div>';
            } else {
                var preview = item.content.substring(0, 150).replace(/\n/g, ' ');
                if (item.content.length > 150) preview += '…';
                html += '<div style="display:flex; justify-content:space-between; align-items:flex-start; gap:8px;">';
                html += '<div style="flex:1; overflow:hidden; color:#cbd5e1; font-size:0.85em; line-height:1.5; word-break:break-word;">' + self.escapeHtml(preview) + '</div>';
                html += '<span style="color:#475569; font-size:0.72em; white-space:nowrap; flex-shrink:0;">' + timeStr + '</span>';
                html += '</div>';
                html += '<div style="margin-top:6px; text-align:right;">';
                html += '<button class="history-use-btn" data-idx="' + idx + '" style="background:#1e3a5f; color:#60a5fa; border:1px solid #2563eb; border-radius:4px; padding:3px 12px; font-size:0.78em; cursor:pointer; transition:background 0.15s;">填入输入框</button>';
                html += '</div>';
            }
            html += '</div>';
        });
        list.innerHTML = html;

        self._cachedHistoryItems = items;

        list.querySelectorAll('.history-item').forEach(function(el) {
            el.addEventListener('mouseenter', function() { el.style.background = '#1e293b'; el.style.borderColor = '#334155'; });
            el.addEventListener('mouseleave', function() { el.style.background = '#0f172a'; el.style.borderColor = 'transparent'; });
            el.addEventListener('click', function(e) {
                if (e.target.classList.contains('history-use-btn')) return;
                var i = parseInt(el.dataset.idx);
                var t = el.dataset.tab;
                if (self._cachedHistoryItems && self._cachedHistoryItems[i]) {
                    self.showHistoryDetail(self._cachedHistoryItems[i].content, t === 'ai' ? 'AI 工作摘要' : '用户输入', t === 'ai');
                }
            });
        });
        list.querySelectorAll('.history-use-btn').forEach(function(btn) {
            btn.addEventListener('click', function(e) {
                e.stopPropagation();
                var i = parseInt(btn.dataset.idx);
                if (self._cachedHistoryItems && self._cachedHistoryItems[i]) {
                    var input = document.getElementById('combinedFeedbackText');
                    if (input) {
                        input.value = self._cachedHistoryItems[i].content;
                        input.disabled = false;
                        input.focus();
                        self.saveFeedbackDraft();
                        Utils.showMessage('已填入输入框', Utils.CONSTANTS.MESSAGE_SUCCESS);
                    }
                }
            });
        });
    };

    FeedbackApp.prototype.showHistoryDetail = function(content, title, isMarkdown) {
        var overlay = document.getElementById('historyDetailOverlay');
        if (!overlay) {
            overlay = document.createElement('div');
            overlay.id = 'historyDetailOverlay';
            overlay.style.cssText = 'position:fixed; inset:0; background:rgba(0,0,0,0.55); backdrop-filter:blur(4px); z-index:9999; display:flex; align-items:center; justify-content:center; padding:16px;';
            overlay.innerHTML = '<div id="historyDetailBox" style="background:#1e293b; border:1px solid #334155; border-radius:12px; max-width:900px; width:100%; max-height:92vh; display:flex; flex-direction:column; overflow:hidden; box-shadow:0 20px 60px rgba(0,0,0,0.5);">'
                + '<div id="historyDetailHeader" style="display:flex; justify-content:space-between; align-items:center; padding:14px 20px; border-bottom:1px solid #334155; background:#162032;">'
                + '<span id="historyDetailTitle" style="font-weight:600; color:#e2e8f0; font-size:0.95em;"></span>'
                + '<button id="historyDetailClose" style="background:none; border:none; color:#94a3b8; font-size:1.3em; cursor:pointer; padding:4px 8px; border-radius:4px; transition:background 0.15s;" onmouseenter="this.style.background=\'#334155\'" onmouseleave="this.style.background=\'none\'">✕</button>'
                + '</div>'
                + '<div id="historyDetailContent" style="padding:20px; overflow-y:auto; color:#cbd5e1; font-size:0.88em; line-height:1.7; word-break:break-word;"></div>'
                + '</div>';
            document.body.appendChild(overlay);
            overlay.addEventListener('click', function(e) {
                if (e.target === overlay) overlay.style.display = 'none';
            });
            document.getElementById('historyDetailClose').addEventListener('click', function() {
                overlay.style.display = 'none';
            });
        }
        document.getElementById('historyDetailTitle').textContent = title;
        var contentEl = document.getElementById('historyDetailContent');
        if (isMarkdown && this.uiManager && typeof this.uiManager.renderMarkdownSafely === 'function') {
            contentEl.innerHTML = this.uiManager.renderMarkdownSafely(content);
            contentEl.style.whiteSpace = 'normal';
            contentEl.classList.add('history-markdown-body');
        } else {
            contentEl.textContent = content;
            contentEl.style.whiteSpace = 'pre-wrap';
            contentEl.classList.remove('history-markdown-body');
        }
        overlay.style.display = 'flex';
    };

    // 將 FeedbackApp 暴露給全域
    window.MCPFeedback.FeedbackApp = FeedbackApp;
    window.FeedbackApp = FeedbackApp;

})();
