/*
 * 管理员后台入口模块：装配会话、聊天、档案、结果与问卷管理功能。
 * 作者: @ccfork
 */
import { apiUrl } from './api.js';
import { els, initElements, setMobileView, state } from './state.js';
import { bindChatPanel } from './chat.js';
import { bindProfileModal } from './profile.js';
import { bindQuestionnairePanel, loadQuestionnaire } from './questionnaire.js';
import { bindResultsPanel, loadQuestionsData } from './results.js';
import { selectSession } from './chat.js';
import { bindSessionList, loadSessions } from './sessions.js';
import { bindWatchPanel, clearWatchTimers } from './watch.js';

function bindMobileTabs() {
    document.querySelectorAll('.mobile-tabs button').forEach((btn) => {
        btn.addEventListener('click', () => setMobileView(btn.dataset.view));
    });
}

async function initEmojiPanel() {
    state.emojiPanel = window.ChatEmoji.createPanel({
        host: els.adminEmojiHost,
        trigger: els.adminEmojiToggle,
        input: els.adminMessageInput,
        apiUrl
    });
    await state.emojiPanel.init();
}

async function init() {
    initElements();
    bindSessionList(selectSession);
    bindChatPanel();
    bindProfileModal();
    bindResultsPanel();
    bindQuestionnairePanel();
    bindWatchPanel();
    bindMobileTabs();
    document.addEventListener('keydown', (event) => {
        if (event.key === 'Escape') state.emojiPanel?.close();
    });
    await loadQuestionsData();
    await loadQuestionnaire();
    await initEmojiPanel();
    await loadSessions();
    state.sessionPollInterval = setInterval(loadSessions, 1800);
}

window.addEventListener('beforeunload', () => {
    if (state.pollingInterval) clearInterval(state.pollingInterval);
    if (state.sessionPollInterval) clearInterval(state.sessionPollInterval);
    clearWatchTimers();
});
document.addEventListener('DOMContentLoaded', init);
