(function () {
  'use strict';
  document.querySelectorAll('[data-lesson-practice]').forEach(function (box) {
    var questions = Array.from(box.querySelectorAll('[data-answer]'));
    var check = box.querySelector('[data-check]');
    var reset = box.querySelector('[data-reset]');
    var result = box.querySelector('[data-result]');
    var notes = box.querySelector('details');
    var reported = false;
    if (!questions.length || !check || !reset || !result || !notes) return;
    box.querySelector('[data-controls]').hidden = false;
    check.addEventListener('click', function () {
      var empty = questions.find(function (q) { return !q.querySelector('select').value; });
      if (empty) {
        result.textContent = 'Choose an answer for each question first.';
        empty.querySelector('select').focus();
        return;
      }
      var score = questions.filter(function (q) {
        return q.querySelector('select').value === q.dataset.answer;
      }).length;
      result.textContent = 'You got ' + score + ' out of ' + questions.length + ' correct. Read the answer notes below.';
      notes.open = true;
      if (!reported && typeof window.ym === 'function' && location.hostname === 'iswearenglish.com') {
        try {
          window.ym(94630727, 'reachGoal', 'iswear_pilot_practice_checked', {
            lesson: box.dataset.lessonPractice, correct: score, questions: questions.length
          });
          reported = true;
        } catch (ignored) { /* Practice remains usable if analytics is unavailable. */ }
      }
    });
    reset.addEventListener('click', function () {
      questions.forEach(function (q) { q.querySelector('select').value = ''; });
      result.textContent = '';
      notes.open = false;
      questions[0].querySelector('select').focus();
    });
    box.addEventListener('change', function () {
      result.textContent = '';
    });
  });
}());
