/*
 * 问卷结果模块：展示 chat 端答过的题目和选择文本。
 * 作者: @ccfork
 */
import { apiGet } from './api.js';
import { els, setMobileView, state } from './state.js';
import { answerText, escapeHtml, getQuestionByAnswer, plainQuestionText } from './utils.js';

export function closeResultsPanel() {
    els.resultsPanel.classList.remove('active');
    els.adminShell.classList.remove('has-results');
}

export async function loadQuestionsData() {
    try {
        const res = await fetch(`questions.php?t=${Date.now()}`);
        state.questionsData = await res.json();
    } catch (error) {
        state.questionsData = [];
    }
}

async function showResultsPanel() {
    if (!state.currentSessionId) return;
    els.resultsPanel.classList.add('active');
    els.questionnairePanel.classList.remove('active');
    els.adminShell.classList.add('has-results');
    els.adminShell.classList.remove('has-questionnaire');
    setMobileView('results');
    try {
        const data = await apiGet('get_user_results', { session_id: state.currentSessionId });
        if (data.success && data.results && Array.isArray(data.results.answers)) {
            const answers = (data.results.answers || [])
                .map((ans, i) => ({ ans, i }))
                .filter((item) => item.ans);
            if (!answers.length) {
                els.resultsContent.innerHTML = '<div class="results-empty-shell"><div class="empty-state">暂无答题结果～</div></div>';
                return;
            }
            els.resultsContent.innerHTML = answers.map(({ ans, i }) => {
                const question = getQuestionByAnswer(state.questionsData, ans, i);
                const questionText = ans.questionText || (question ? plainQuestionText(question.text) : '未知题目');
                const answer = ans.answerText || answerText(question, ans);
                return `
                    <div class="answer-item">
                        <strong>${escapeHtml(questionText)}</strong>
                        <p>${escapeHtml(answer)}</p>
                    </div>
                `;
            }).join('');
        } else {
            els.resultsContent.innerHTML = '<div class="results-empty-shell"><div class="empty-state">暂无答题结果～</div></div>';
        }
    } catch (error) {
        console.error(error);
    }
}

export function bindResultsPanel() {
    els.resultsBtn.addEventListener('click', showResultsPanel);
    els.closeResultsBtn.addEventListener('click', () => {
        closeResultsPanel();
        setMobileView('chat');
    });
}
