/* EireneEduCloud — QuizEngine
   Eirene Technologies Limited
   Renders a multiple-choice quiz with instant feedback, explanations and scoring. */
(function (w) {
  function el(tag, cls, html) {
    var e = document.createElement(tag);
    if (cls) e.className = cls;
    if (html != null) e.innerHTML = html;
    return e;
  }

  function QuizEngine(mount, quiz, lessonId, onComplete) {
    this.mount = typeof mount === 'string' ? document.getElementById(mount) : mount;
    this.questions = (quiz && quiz.questions) || [];
    this.lessonId = lessonId;
    this.onComplete = onComplete;
    this.answered = {};
    this.score = 0;
  }

  QuizEngine.prototype.render = function () {
    var self = this;
    this.mount.innerHTML = '';
    var head = el('div', 'quiz-head',
      '<h3>Quick Check</h3><p class="muted">' + this.questions.length +
      ' questions · choose an answer to see instant feedback.</p>');
    this.mount.appendChild(head);

    this.questions.forEach(function (q, qi) {
      var block = el('div', 'quiz');
      block.appendChild(el('div', 'q', '<span class="qnum">' + (qi + 1) + '.</span> ' + q.question));
      var opts = el('div', 'opts');
      q.options.forEach(function (opt, oi) {
        var b = el('button', 'opt');
        b.type = 'button';
        b.innerHTML = '<span class="bullet">' + String.fromCharCode(65 + oi) + '</span>' + opt;
        b.addEventListener('click', function () { self._answer(block, q, qi, oi, opts); });
        opts.appendChild(b);
      });
      block.appendChild(opts);
      block.appendChild(el('div', 'explain', ''));
      self.mount.appendChild(block);
    });

    var foot = el('div', 'qresult');
    foot.id = 'quiz-result-' + this.lessonId;
    this.mount.appendChild(foot);
  };

  QuizEngine.prototype._answer = function (block, q, qi, chosen, optsWrap) {
    if (this.answered[qi] != null) return; // lock after first answer
    this.answered[qi] = chosen;
    var buttons = optsWrap.querySelectorAll('.opt');
    for (var i = 0; i < buttons.length; i++) {
      buttons[i].disabled = true;
      if (i === q.correct) buttons[i].classList.add('correct');
      if (i === chosen && chosen !== q.correct) buttons[i].classList.add('wrong');
    }
    var correct = chosen === q.correct;
    if (correct) this.score++;
    var ex = block.querySelector('.explain');
    ex.className = 'explain show ' + (correct ? 'ok' : 'no');
    ex.innerHTML = (correct ? '✓ Correct! ' : '✗ Not quite. ') + q.explanation;

    if (Object.keys(this.answered).length === this.questions.length) this._finish();
  };

  QuizEngine.prototype._finish = function () {
    var total = this.questions.length;
    var pct = Math.round(this.score / total * 100);
    var rec = null;
    if (w.ProgressTracker) rec = w.ProgressTracker.recordQuiz(this.lessonId, this.score, total);
    var msg = pct >= 80 ? 'Excellent work! 🌟' : pct >= 50 ? 'Good effort — review and try again. 💪' : 'Keep practising — you can do it! 📚';
    var foot = document.getElementById('quiz-result-' + this.lessonId);
    if (foot) {
      foot.className = 'qresult show';
      foot.innerHTML = '<div class="score-ring" style="--p:' + pct + '"><span>' + pct + '%</span></div>' +
        '<div><strong>You scored ' + this.score + ' / ' + total + '.</strong><br>' + msg +
        '<br><span class="muted">Best score saved on this device.</span></div>' +
        '<button class="btn btn-ghost" type="button" id="retry-' + this.lessonId + '">Try again</button>';
      var self = this;
      var rt = document.getElementById('retry-' + this.lessonId);
      if (rt) rt.addEventListener('click', function () { self.answered = {}; self.score = 0; self.render(); });
    }
    if (this.onComplete) this.onComplete(this.score, total, rec);
  };

  w.QuizEngine = QuizEngine;
})(window);
