/*
 * 管理员后台工具函数：文本转义、时间格式、问卷答案格式化。
 * 作者: @ccfork
 */
export function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text == null ? '' : String(text);
    return div.innerHTML;
}

export function formatTime(ts) {
    if (!ts) return '';
    const d = new Date(Number(ts) * 1000);
    const now = new Date();
    if (d.toDateString() === now.toDateString()) {
        return d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    }
    return d.toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric' });
}

export function sessionLabel(session) {
    return session.remark || session.user_id || session.id;
}

export function plainQuestionText(text) {
    const div = document.createElement('div');
    div.innerHTML = text || '';
    return div.textContent || div.innerText || '未知题目';
}

export function getQuestionByAnswer(questions, answer, fallbackIndex) {
    const id = answer && answer.id !== undefined ? answer.id : fallbackIndex;
    return questions.find((question) => Number(question.id) === Number(id)) || questions[fallbackIndex] || null;
}

export function optionLabel(question, value) {
    if (!question || !question.options) return String(value ?? '');
    const option = question.options.find((item) => String(item.value) === String(value));
    return option ? option.label : String(value ?? '');
}

export function answerText(question, answer) {
    if (!answer) return '未作答';
    if (answer.skipped) return '跳过 / 不想说';
    if (answer.answerValue !== undefined) return optionLabel(question, answer.answerValue);
    if (Array.isArray(answer.selectedOptions)) {
        return answer.selectedOptions.map((value) => optionLabel(question, value)).join('、') || '未选择';
    }
    return '未记录答案';
}
