// @ts-nocheck
import { useChatActionStore } from '../stores/chatActions';
import { normalizeScrollLock } from '../composables/useScrollControl';
import { setupShowImageObserver, teardownShowImageObserver } from './bootstrap';
import { debugLog } from './methods/common';

export function created() {
    const actionStore = useChatActionStore();
    actionStore.registerDependencies({
        pushToast: (payload) => this.uiPushToast(payload),
        autoResizeInput: () => this.autoResizeInput(),
        focusComposer: () => {
            const inputEl = this.getComposerElement('stadiumInput');
            if (inputEl && typeof inputEl.focus === 'function') {
                inputEl.focus();
            }
        },
        isConnected: () => this.isConnected,
        getSocket: () => this.socket,
        downloadResource: (url, filename) => this.downloadResource(url, filename)
    });
}

export async function mounted() {
    debugLog('Vue应用已挂载');
    if (window.ensureCsrfToken) {
        window.ensureCsrfToken().catch((err) => {
            console.warn('CSRF token 初始化失败:', err);
        });
    }
    // 并行启动路由解析与实时连接，避免等待路由加载阻塞思考模式同步
    const routePromise = this.bootstrapRoute();
    const socketPromise = this.initSocket();
    await routePromise;
    await socketPromise;
    this.$nextTick(() => {
        this.ensureScrollListener();
        // 刷新后若无输出，自动解锁滚动锁定
        normalizeScrollLock(this);
    });
    setupShowImageObserver();

    // 立即加载初始数据（并行获取状态，优先同步运行模式）
    this.loadInitialData();

    // 注册全局事件处理器（用于任务轮询）
    (window as any).__taskEventHandler = (event: any) => {
        if (typeof this.handleTaskEvent === 'function') {
            this.handleTaskEvent(event);
        }
    };

    // 立即尝试恢复运行中的任务（不延迟）
    if (typeof this.restoreTaskState === 'function') {
        this.restoreTaskState();
    }

    document.addEventListener('click', this.handleClickOutsideQuickMenu);
    document.addEventListener('click', this.handleClickOutsidePanelMenu);
    document.addEventListener('click', this.handleClickOutsideHeaderMenu);
    document.addEventListener('click', this.handleClickOutsideMobileMenu);
    window.addEventListener('popstate', this.handlePopState);
    window.addEventListener('keydown', this.handleMobileOverlayEscape);
    this.setupMobileViewportWatcher();

    this.subAgentFetch();
    this.subAgentStartPolling();

    this.$nextTick(() => {
        this.autoResizeInput();
    });
    this.resourceBindContainerVisibilityWatcher();
    this.resourceStartContainerStatsPolling();
    this.resourceStartProjectStoragePolling();
    this.resourceStartUsageQuotaPolling();
}

export function beforeUnmount() {
    // 停止任务轮询
    try {
        const { useTaskStore } = require('../stores/task');
        const taskStore = useTaskStore();
        taskStore.stopPolling();
    } catch (error) {
        // ignore
    }

    document.removeEventListener('click', this.handleClickOutsideQuickMenu);
    document.removeEventListener('click', this.handleClickOutsidePanelMenu);
    document.removeEventListener('click', this.handleClickOutsideHeaderMenu);
    document.removeEventListener('click', this.handleClickOutsideMobileMenu);
    window.removeEventListener('popstate', this.handlePopState);
    window.removeEventListener('keydown', this.handleMobileOverlayEscape);
    this.teardownMobileViewportWatcher();
    this.subAgentStopPolling();
    this.resourceStopContainerStatsPolling();
    this.resourceStopProjectStoragePolling();
    this.resourceStopUsageQuotaPolling();
    teardownShowImageObserver();
    if (this.titleTypingTimer) {
        clearInterval(this.titleTypingTimer);
        this.titleTypingTimer = null;
    }
    const cleanup = this.destroyEasterEggEffect(true);
    if (cleanup && typeof cleanup.catch === 'function') {
        cleanup.catch(() => {});
    }
}
