<?php
/**
 * 主问卷页面：读取当前题套并联动悬浮会话入口。
 * 作者: @ccfork
 */
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes, viewport-fit=cover">
    <title>🌸 少女心笔记本 · 一问一答小问卷 🌸</title>
    <link rel="stylesheet" href="scrollbar.css?v=20260615a">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            background: linear-gradient(145deg, #fff5f9 0%, #ffe4ef 100%);
            font-family: -apple-system, 'Segoe UI', 'Quicksand', system-ui, 'Helvetica Neue', sans-serif;
            padding: 0;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .notebook {
            max-width: 600px;
            width: 100%;
            margin: 0 auto;
            background: #ffffffea;
            min-height: 100vh;
            border-radius: 0;
            box-shadow: none;
            padding: 0.8rem 1rem 1rem;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }
        .header {
            text-align: center;
            margin-bottom: 0.5rem;
            flex-shrink: 0;
        }
        .header h1 {
            font-size: 1.6rem;
            background: linear-gradient(135deg, #f7a1c1, #ff8bb0);
            background-clip: text;
            -webkit-background-clip: text;
            color: transparent;
            letter-spacing: -0.3px;
        }
        .header .sub {
            background: #ffeef4;
            border-radius: 40px;
            padding: 0.2rem 0.8rem;
            display: inline-block;
            font-size: 0.7rem;
            color: #bc6f8c;
            margin-top: 0.2rem;
        }
        .progress-badge {
            margin-top: 0.3rem;
            font-size: 0.65rem;
            background: #ffe0e9;
            display: inline-block;
            padding: 2px 12px;
            border-radius: 30px;
            color: #bc6f8c;
        }
        #mainContent {
            flex: 1;
            display: flex;
            flex-direction: column;
        }
        .question-card {
            background: #ffffff;
            border-radius: 28px;
            padding: 1rem 1rem;
            margin: 0.3rem 0 0.5rem;
            box-shadow: 0 4px 12px #ffdae7;
            border: 1px solid #ffd1df;
        }
        .q-num {
            background: #ffb7cb;
            color: white;
            border-radius: 30px;
            padding: 2px 12px;
            font-size: 0.65rem;
            display: inline-block;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        .q-text {
            font-size: 1rem;
            font-weight: 700;
            color: #592e3f;
            margin-bottom: 1rem;
            line-height: 1.4;
        }
        .options-area {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
            margin-top: 0.2rem;
        }
        .option-btn {
            background: #fef6f9;
            border: 1.5px solid #ffc1d4;
            border-radius: 50px;
            padding: 10px 14px;
            font-size: 0.85rem;
            font-weight: 500;
            color: #673f50;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 10px;
            transition: 0.1s;
        }
        .option-btn:active {
            background: #ffeef4;
            transform: scale(0.98);
        }
        .option-radio-marker {
            width: 18px;
            height: 18px;
            border-radius: 50%;
            border: 2px solid #f09dbb;
            background: white;
            display: inline-block;
            flex-shrink: 0;
        }
        .option-btn.selected .option-radio-marker {
            background: #ff8aac;
            border-color: #ff8aac;
            box-shadow: inset 0 0 0 2px white;
        }
        .multi-option {
            display: flex;
            align-items: center;
            gap: 10px;
            background: #fef6f9;
            border: 1.5px solid #ffc1d4;
            border-radius: 50px;
            padding: 10px 14px;
            cursor: pointer;
        }
        .multi-option label {
            flex: 1;
            font-size: 0.85rem;
            font-weight: 500;
            color: #673f50;
            cursor: pointer;
        }
        .option-check {
            width: 18px;
            height: 18px;
            accent-color: #f48fb1;
            flex-shrink: 0;
            cursor: pointer;
        }
        .nav-buttons {
            display: flex;
            justify-content: space-between;
            gap: 12px;
            margin-top: 0.5rem;
            margin-bottom: 0.3rem;
        }
        .nav-btn {
            background: #ffe2ec;
            border: none;
            padding: 10px 16px;
            border-radius: 50px;
            font-weight: 600;
            color: #b35573;
            cursor: pointer;
            font-size: 0.85rem;
            flex: 1;
            text-align: center;
        }
        .nav-btn.primary {
            background: #ff8aac;
            color: white;
            box-shadow: 0 2px 4px #ffbbd1;
        }
        .nav-btn:active {
            transform: scale(0.97);
        }
        .nav-btn:disabled {
            opacity: 0.4;
            transform: none;
        }
        .knowledge-mini {
            background: #fff2f7;
            border-radius: 20px;
            padding: 8px 12px;
            margin: 0.3rem 0 0;
            font-size: 0.7rem;
            color: #c26483;
            border-left: 5px solid #ffa9c4;
        }
        .result-area {
            background: #fff0f5;
            border-radius: 28px;
            padding: 1rem;
            text-align: center;
            margin: 0.5rem 0;
        }
        .chat-entry {
            text-align: center;
            margin: 0.8rem 0 0.3rem;
            padding: 0.5rem;
            background: #fff0f5;
            border-radius: 60px;
        }
        .chat-link {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: linear-gradient(135deg, #f8a5c2, #ff8bb0);
            color: white;
            padding: 8px 20px;
            border-radius: 40px;
            text-decoration: none;
            font-weight: 600;
            font-size: 0.85rem;
            transition: 0.1s;
        }
        .chat-link:active {
            transform: scale(0.96);
        }
        .floating-chat-entry {
            position: fixed;
            right: 16px;
            bottom: calc(18px + env(safe-area-inset-bottom));
            z-index: 30;
            display: none;
            align-items: center;
            justify-content: center;
            width: 54px;
            height: 54px;
            border-radius: 50%;
            color: #fff;
            background: linear-gradient(135deg, #f8a5c2, #ff8bb0);
            box-shadow: 0 8px 18px rgba(241, 147, 177, 0.34);
            text-decoration: none;
        }
        .floating-chat-entry.has-message {
            display: inline-flex;
            animation: paperPulse 1.15s ease-in-out infinite;
        }
        .floating-chat-entry .message-dot {
            position: absolute;
            top: 4px;
            right: 4px;
            width: 14px;
            height: 14px;
            border: 2px solid #fff;
            border-radius: 50%;
            background: #ff5f8f;
        }
        @keyframes paperPulse {
            0%, 100% { transform: translateY(0) scale(1); }
            50% { transform: translateY(-5px) scale(1.06); }
        }
        .footer {
            font-size: 0.6rem;
            text-align: center;
            margin-top: 0.5rem;
            color: #e9a3bd;
            border-top: 1px dashed #ffcfdf;
            padding-top: 0.6rem;
            flex-shrink: 0;
        }
        .loading {
            text-align: center;
            padding: 2rem;
            color: #ff8aac;
        }
        .explain-card {
            background: #ffffff;
            border-radius: 28px;
            padding: 1.2rem;
            margin: 0.3rem 0;
            box-shadow: 0 4px 12px #ffdae7;
            border: 1px solid #ffd1df;
        }
        .explain-title {
            font-size: 1.1rem;
            font-weight: 700;
            color: #c76e8d;
            margin-bottom: 0.8rem;
        }
        .explain-content {
            font-size: 0.85rem;
            line-height: 1.5;
            color: #6a4b59;
            margin-bottom: 1rem;
        }
        @media (min-width: 600px) {
            .notebook {
                border-radius: 32px;
                min-height: auto;
                margin: 1rem auto;
                box-shadow: 0 20px 35px rgba(241, 147, 177, 0.2);
            }
        }
    </style>
</head>
<body>
<div class="notebook">
    <div class="header">
        <h1 id="siteTitle">🌸 少女心笔记本 🌸</h1>
        <div class="sub" id="siteSubtitle">💌 每道题都有「不懂就看百科」</div>
        <div class="progress-badge" id="progressIndicator">✨ 加载中... ✨</div>
    </div>
    
    <div id="mainContent"><div class="loading">🍬 正在打开笔记本...</div></div>
    
    <!-- 聊天入口 -->
    <div class="chat-entry" id="chatEntry" style="display:none;">
        <a href="#" id="chatLink" class="chat-link">💬 去聊天室 · 和AI/管理员说悄悄话</a>
    </div>
    
    <div class="footer">🌈 选「不懂」会弹出小百科 · 随时可放弃回答</div>
</div>
<a class="floating-chat-entry" id="floatingChatEntry" href="#" aria-label="打开小纸条">
    💬<span class="message-dot"></span>
</a>

<script>
// ==================== 问卷数据 ====================
let questionsData = [], currentQuestionObj = null, currentIndex = 0, userAnswers = [], isInExplainMode = false;
let currentQuestionnaireSet = { id: 'default', title: '少女心笔记本', enabled: true };
let chatSessionId = null;

// 获取或创建会话ID（用于与聊天室联动）
function initChatSession() {
    const urlParams = new URLSearchParams(window.location.search);
    chatSessionId = urlParams.get('session_id');
    if (!chatSessionId) {
        chatSessionId = localStorage.getItem('chat_session_id');
        if (!chatSessionId) {
            chatSessionId = 'user_' + Date.now() + '_' + Math.random().toString(36).substr(2, 8);
            localStorage.setItem('chat_session_id', chatSessionId);
        }
    }
    // 更新聊天入口链接
    const chatLink = document.getElementById('chatLink');
    if (chatLink) {
        chatLink.href = `chat.php?session_id=${chatSessionId}`;
        document.getElementById('chatEntry').style.display = 'block';
    }
    const floatingEntry = document.getElementById('floatingChatEntry');
    if (floatingEntry) floatingEntry.href = `chat.php?session_id=${chatSessionId}`;
}

// 轮询小纸条消息，答题中也能收到提醒
async function pollChatNotice() {
    if (!chatSessionId) return;
    try {
        const res = await fetch(`chat_api.php?action=get_messages&session_id=${chatSessionId}&last_id=0&t=${Date.now()}`);
        const data = await res.json();
        const clearSeq = Number(data.clear_seq || 0);
        const storedClearSeq = Number(localStorage.getItem(`chat_clear_seq_${chatSessionId}`) || 0);
        if (clearSeq > storedClearSeq) {
            localStorage.setItem(`chat_clear_seq_${chatSessionId}`, String(clearSeq));
            localStorage.setItem(`chat_seen_admin_${chatSessionId}`, String(data.clear_after_id || 0));
        }
        const maxAdminId = data.success ? Math.max(0, ...(data.messages || [])
            .filter(msg => msg.sender === 'admin')
            .map(msg => Number(msg.id || 0))) : 0;
        const seenAdminId = Number(localStorage.getItem(`chat_seen_admin_${chatSessionId}`) || 0);
        const hasAdminMessage = maxAdminId > seenAdminId;
        const entry = document.getElementById('floatingChatEntry');
        if (entry) entry.classList.toggle('has-message', hasAdminMessage);
    } catch(e) {}
}

async function registerChatSession() {
    if (!chatSessionId) return;
    try {
        await fetch('chat_api.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ action: 'register_session', session_id: chatSessionId, source: 'questionnaire' })
        });
    } catch(e) {}
}

// 当前题套决定页面标题和题目，避免标题与题目分离。
function applyQuestionnaireSet(setData) {
    currentQuestionnaireSet = {
        id: setData && setData.id ? setData.id : 'default',
        title: setData && setData.title ? setData.title : '少女心笔记本',
        enabled: !(setData && setData.enabled === false)
    };
    document.title = currentQuestionnaireSet.title;
    const siteTitle = document.getElementById('siteTitle');
    if (siteTitle) siteTitle.textContent = currentQuestionnaireSet.title;
}

// 加载题目数据
async function loadQuestions() {
    try {
        const configResponse = await fetch('admin/api/questionnaire.php?action=get&t=' + Date.now());
        const configData = await configResponse.json();
        if (!configData.success) throw new Error(configData.error || '题套读取失败');
        const activeSet = configData.active_set || {
            id: configData.config && configData.config.set_id ? configData.config.set_id : 'default',
            title: configData.config && configData.config.title ? configData.config.title : '少女心笔记本',
            enabled: !(configData.config && configData.config.enabled === false),
            questions: configData.questions || []
        };
        applyQuestionnaireSet(activeSet);
        if (activeSet.enabled === false) {
            document.getElementById('mainContent').innerHTML = '<div class="result-area">💌 这里现在是小纸条模式，可以直接去聊天室～</div>';
            document.getElementById('progressIndicator').innerHTML = '💌 小纸条模式';
            return;
        }
        const data = Array.isArray(activeSet.questions) ? activeSet.questions : [];
        if (!data || !data.length) throw new Error('数据为空');
        questionsData = data;
        userAnswers = new Array(questionsData.length).fill(null);
        currentIndex = 0;
        renderCurrentQuestion();
    } catch (error) {
        document.getElementById('mainContent').innerHTML = '<div class="loading">🌸 加载失败，请刷新<br>' + error.message + '</div>';
    }
}

function renderCurrentQuestion() {
    if (!questionsData.length) return;
    if (currentIndex >= questionsData.length) { finishAndShowScore(); return; }
    currentQuestionObj = questionsData[currentIndex];
    isInExplainMode = false;
    document.getElementById('progressIndicator').innerHTML = `✨ 第${currentIndex+1}/${questionsData.length} ✨`;
    const mainDiv = document.getElementById('mainContent');
    
    mainDiv.innerHTML = `
        <div class="question-card">
            <div class="q-num">🌸 第${currentIndex+1}题</div>
            <div class="q-text">${currentQuestionObj.text}</div>
            <div class="options-area" id="optionsArea"></div>
        </div>
        <div class="nav-buttons">
            <button class="nav-btn" id="prevBtn" ${currentIndex === 0 ? 'disabled' : ''}>◀ 上一题</button>
            <button class="nav-btn primary" id="nextBtn">下一题 ▶</button>
        </div>
        <div class="knowledge-mini">💡 选"🤔 不懂"会弹出小百科～</div>
    `;
    
    const optionsArea = document.getElementById('optionsArea');
    
    if (currentQuestionObj.type === 'single') {
        currentQuestionObj.options.forEach(opt => {
            const isSkip = opt.is_skip === true;
            const isDontKnow = opt.is_dont_know === true;
            const btn = document.createElement('div');
            btn.className = 'option-btn';
            btn.setAttribute('data-value', opt.value !== undefined ? opt.value : '');
            btn.setAttribute('data-next', opt.next || '');
            btn.setAttribute('data-is-skip', isSkip);
            btn.setAttribute('data-is-dontknow', isDontKnow);
            btn.innerHTML = `<span class="option-radio-marker"></span><span>${opt.label}</span>`;
            btn.onclick = (e) => {
                document.querySelectorAll('.option-btn').forEach(b => b.classList.remove('selected'));
                btn.classList.add('selected');
            };
            optionsArea.appendChild(btn);
        });
    } else if (currentQuestionObj.type === 'multi') {
        currentQuestionObj.options.forEach(opt => {
            const isSkip = opt.is_skip === true;
            const isDontKnow = opt.is_dont_know === true;
            const div = document.createElement('div');
            div.className = 'multi-option';
            const cb = document.createElement('input');
            cb.type = 'checkbox';
            cb.className = 'option-check';
            cb.setAttribute('data-value', opt.value);
            cb.setAttribute('data-next', opt.next || '');
            cb.setAttribute('data-is-dontknow', isDontKnow);
            const label = document.createElement('label');
            label.innerText = opt.label;
            div.appendChild(cb);
            div.appendChild(label);
            div.onclick = (e) => {
                if (e.target !== cb) cb.checked = !cb.checked;
            };
            optionsArea.appendChild(div);
        });
    }
    
    // 恢复之前答案
    const prevAnswer = userAnswers[currentIndex];
    if (prevAnswer && !prevAnswer.skipped) {
        if (currentQuestionObj.type === 'single' && prevAnswer.answerValue !== undefined) {
            document.querySelectorAll('.option-btn').forEach(btn => {
                if (btn.getAttribute('data-value') == prevAnswer.answerValue) btn.classList.add('selected');
            });
        } else if (currentQuestionObj.type === 'multi' && prevAnswer.selectedOptions) {
            document.querySelectorAll('.option-check').forEach(cb => {
                if (prevAnswer.selectedOptions.includes(cb.getAttribute('data-value'))) cb.checked = true;
            });
        }
    }
    
    document.getElementById('prevBtn').onclick = goToPrev;
    document.getElementById('nextBtn').onclick = goToNext;
}

function getCurrentSelected() {
    const q = currentQuestionObj;
    if (!q) return null;
    if (q.type === 'single') {
        const selected = document.querySelector('.option-btn.selected');
        if (!selected) return null;
        return {
            type: 'single',
            value: selected.getAttribute('data-value'),
            next: selected.getAttribute('data-next'),
            isSkip: selected.getAttribute('data-is-skip') === 'true',
            isDontKnow: selected.getAttribute('data-is-dontknow') === 'true'
        };
    } else if (q.type === 'multi') {
        const checkboxes = document.querySelectorAll('.option-check:checked');
        let selectedVals = [];
        let hasDontKnow = false;
        for (let cb of checkboxes) {
            const val = cb.getAttribute('data-value');
            const isDontKnow = cb.getAttribute('data-is-dontknow') === 'true';
            if (val && !isDontKnow) selectedVals.push(val);
            if (isDontKnow) hasDontKnow = true;
        }
        if (selectedVals.length === 0 && !hasDontKnow) return null;
        if (hasDontKnow) return { type: 'multi', isDontKnow: true, isSkip: false };
        return { type: 'multi', value: selectedVals, isDontKnow: false, isSkip: false };
    }
    return null;
}

function optionTextByValue(question, value) {
    const option = (question.options || []).find(opt => String(opt.value) === String(value));
    return option ? option.label : String(value ?? '');
}

function answerTextForSelected(question, selected) {
    if (!selected) return '未作答';
    if (selected.isSkip) return '跳过 / 不想说';
    if (selected.isDontKnow) return '查看小百科';
    if (selected.type === 'single') return optionTextByValue(question, selected.value);
    if (selected.type === 'multi') return (selected.value || []).map(value => optionTextByValue(question, value)).join('、') || '未选择';
    return '未记录答案';
}

function saveCurrentAnswer(selected) {
    if (!selected) return false;
    const baseAnswer = {
        id: currentQuestionObj.id,
        questionText: currentQuestionObj.text,
        answerText: answerTextForSelected(currentQuestionObj, selected)
    };
    if (selected.isSkip) {
        userAnswers[currentIndex] = { ...baseAnswer, skipped: true, score: null };
        return true;
    }
    if (selected.type === 'single') {
        let score = (selected.value && !isNaN(parseFloat(selected.value))) ? parseFloat(selected.value) : null;
        userAnswers[currentIndex] = { ...baseAnswer, skipped: false, answerValue: selected.value, score: score };
    } else if (selected.type === 'multi') {
        let score = computeMultiScore(currentQuestionObj, selected.value);
        userAnswers[currentIndex] = { ...baseAnswer, skipped: false, selectedOptions: selected.value, score: score };
    }
    return true;
}

function computeMultiScore(q, selectedValues) {
    if (!selectedValues || !selectedValues.length) return null;
    if (q.id === 1) {
        let hasNoReaction = selectedValues.includes('no_reaction');
        let otherCount = selectedValues.filter(v => v !== 'no_reaction').length;
        if (hasNoReaction && otherCount === 0) return 1;
        if (otherCount >= 3) return 4;
        if (otherCount === 2) return 3;
        if (otherCount === 1) return 2;
        return 1;
    }
    if (q.id === 8) {
        const correctSet = new Set(['consent','condom','plan']);
        let hasWrong = selectedValues.includes('wrong');
        let correctCount = selectedValues.filter(v => correctSet.has(v)).length;
        if (!hasWrong && correctCount === 3) return 4;
        if (!hasWrong && correctCount === 2) return 2;
        if (!hasWrong && correctCount === 1) return 1;
        return 0;
    }
    return null;
}

function showExplainPage(explainData, nextQuestionId) {
    isInExplainMode = true;
    const mainDiv = document.getElementById('mainContent');
    mainDiv.innerHTML = `
        <div class="explain-card">
            <div class="explain-title">📖 ${explainData.title}</div>
            <div class="explain-content">${explainData.content}</div>
            <div class="option-btn" id="continueBtn" style="background:#ff8aac; color:white; text-align:center; justify-content:center; margin-top:0.5rem;">
                ✨ 明白啦，继续答题 ✨
            </div>
        </div>
    `;
    document.getElementById('continueBtn').onclick = () => {
        currentIndex = nextQuestionId;
        renderCurrentQuestion();
    };
    document.getElementById('progressIndicator').innerHTML = `📖 学习小百科～`;
}

function goToNext() {
    if (isInExplainMode) return;
    const selected = getCurrentSelected();
    if (!selected) {
        alert("💖 请选择一个选项～");
        return;
    }
    if (selected.isDontKnow && !selected.isSkip && currentQuestionObj.explain_page) {
        userAnswers[currentIndex] = {
            id: currentQuestionObj.id,
            questionText: currentQuestionObj.text,
            answerText: '查看小百科',
            skipped: true,
            score: null
        };
        showExplainPage(currentQuestionObj.explain_page, currentQuestionObj.explain_page.next_question);
        return;
    }
    saveCurrentAnswer(selected);
    if (currentIndex + 1 < questionsData.length) {
        currentIndex++;
        renderCurrentQuestion();
    } else {
        finishAndShowScore();
    }
}

function goToPrev() {
    if (isInExplainMode) return;
    if (currentIndex > 0) {
        const selected = getCurrentSelected();
        if (selected) saveCurrentAnswer(selected);
        currentIndex--;
        renderCurrentQuestion();
    }
}

// 保存答题结果到服务器（供管理员查看）
async function saveResultsToServer(totalScore, totalPossible) {
    if (!chatSessionId) return;
    try {
        const answerCount = userAnswers.filter(a => a && !a.skipped).length;
        await fetch('chat_api.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                action: 'save_results',
                session_id: chatSessionId,
                results: {
                    questionnaireSetId: currentQuestionnaireSet.id,
                    questionnaireTitle: currentQuestionnaireSet.title,
                    totalScore: totalScore,
                    totalPossible: totalPossible,
                    answerCount: answerCount,
                    answers: userAnswers,
                    timestamp: Date.now()
                }
            })
        });
    } catch(e) {
        console.log('保存结果失败:', e);
    }
}

function finishAndShowScore() {
    let totalScore = 0, totalPossible = 0;
    for (let i = 0; i < questionsData.length; i++) {
        const ans = userAnswers[i];
        if (ans && !ans.skipped && typeof ans.score === 'number') {
            totalScore += ans.score;
            totalPossible += 4;
        }
    }
    
    // 保存结果到服务器
    saveResultsToServer(totalScore, totalPossible);
    
    let percent = totalPossible > 0 ? (totalScore / totalPossible) * 100 : 0;
    let starMsg = "";
    if (percent >= 80) starMsg = "🌟🌟🌟🌟🌟 超棒少女觉察力！你尊重身体边界且充满勇气～";
    else if (percent >= 55) starMsg = "🌟🌟🌟🌟 已经很棒啦～ 再多翻翻小知识会更轻松喔 💕";
    else if (percent >= 30) starMsg = "🌟🌟🌟 每个人都有自己的节奏，推荐《半小时漫画青春期》～";
    else starMsg = "🌟🌟 慢慢了解自己就好，你已经超勇敢啦♡";
    
    document.getElementById('mainContent').innerHTML = `
        <div class="result-area">
            <div style="font-size:1rem; font-weight:bold;">🌸 你的总分: ${totalScore} / ${totalPossible} 🌸</div>
            <div style="margin:0.8rem 0;">${starMsg}</div>
            <div style="font-size:0.8rem; color:#c76e8d;">💖 分数只是小参考，你永远最懂自己～</div>
            <button id="restartBtn" style="background:#ffb7cb; margin-top:1rem; padding:8px 24px; border-radius:40px; color:white; border:none; font-size:0.85rem; cursor:pointer;">🔄 重新填写</button>
        </div>
    `;
    document.getElementById('progressIndicator').innerHTML = `✨ 完成啦 ✨`;
    const restartBtn = document.getElementById('restartBtn');
    if (restartBtn) restartBtn.onclick = () => {
        userAnswers.fill(null);
        currentIndex = 0;
        renderCurrentQuestion();
    };
}

// 初始化
initChatSession();
loadQuestions();
registerChatSession();
pollChatNotice();
setInterval(pollChatNotice, 2500);
</script>
</body>
</html>
