summaryrefslogtreecommitdiff
path: root/static/quiz-runtime.js
blob: d6e824dae92175d4110fb3a665e713cb7ea3095a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
 * Quiz Runtime — controla o fluxo de quiz/simulado na página dedicada
 */

const PROGRESS_PREFIX = window.PROGRESS_PREFIX = 'quiz_progress_';

// Estado global do quiz (página de quiz dedicada)
let _qState = {
  questions: [],
  qIndex: 0,
  acertos: 0,
  erros: 0,
  answered: false,
  flipped: false,
};

function nextQuestion() {
  _qState.qIndex++;
  _qState.answered = false;
  _qState.flipped = false;
  if (_qState.qIndex >= _qState.questions.length) {
    showResult();
    return;
  }
  const body = document.getElementById('quiz-body');
  if (!body) return;
  body.classList.add('fade-out');
  setTimeout(() => {
    body.classList.remove('fade-out');
    _renderQuestion(_qState.questions[_qState.qIndex]);
    _saveProgress(window.QUIZ_KEY);
  }, 100);
}

function showResult() {
  const wrap   = document.getElementById('quiz-wrap');
  const result = document.getElementById('quiz-result');
  if (wrap)   wrap.style.display   = 'none';
  if (result) result.style.display = '';
  _buildResult();
  _clearProgress(window.QUIZ_KEY);
  window.scrollTo({ top: 0, behavior: 'smooth' });
}

function restartQuiz() {
  _clearProgress(window.QUIZ_KEY);
  _qState.questions = prepareQuizQuestions(parseQuizBody(
    typeof RAW_QUIZ !== 'undefined' ? RAW_QUIZ : ''
  ));
  _qState.qIndex    = 0;
  _qState.acertos   = 0;
  _qState.erros     = 0;
  _qState.answered  = false;
  _qState.flipped   = false;
  const wrap   = document.getElementById('quiz-wrap');
  const result = document.getElementById('quiz-result');
  if (result) result.style.display = 'none';
  if (wrap)   wrap.style.display   = '';
  _renderQuestion(_qState.questions[0]);
}

function initQuiz() {
  // Só inicializa na página de quiz (onde existe #quiz-body)
  if (!document.getElementById('quiz-body')) return;

  const raw = typeof RAW_QUIZ !== 'undefined' ? RAW_QUIZ : '';
  const key = window.QUIZ_KEY;

  if (!_loadProgress(key)) {
    _qState.questions = prepareQuizQuestions(parseQuizBody(raw));
    _qState.qIndex    = 0;
    _qState.acertos   = 0;
    _qState.erros     = 0;
  }

  _qState.answered = false;
  _qState.flipped  = false;

  const wrap   = document.getElementById('quiz-wrap');
  const result = document.getElementById('quiz-result');
  if (result) result.style.display = 'none';
  if (wrap)   wrap.style.display   = '';

  if (_qState.qIndex >= _qState.questions.length) {
    showResult();
    return;
  }

  _renderQuestion(_qState.questions[_qState.qIndex]);
}

document.addEventListener('DOMContentLoaded', initQuiz);