import { esc, sanitizeHtml } from './sanitize.js';

export function renderQuizQuestions(questions) {
  return (questions || []).map(function(q, idx) {
    var isMulti = q.question_type === 'multi';
    var typeLabel = q.question_type === 'true_false' ? 'True / False'
      : isMulti ? 'Multiple Select'
      : 'Single Choice';
    var inputType = isMulti ? 'checkbox' : 'radio';
    var nameAttr = isMulti ? 'lh-qm-' + q.id : 'lh-q-' + q.id;
    var hint = isMulti ? '<div class="lh-quiz-multi-hint">Select all that apply</div>' : '';

    return '<div class="lh-quiz-q" data-qid="' + q.id + '" data-qtype="' + q.question_type + '">' +
      '<div class="lh-quiz-q-header">' +
        '<span class="lh-quiz-q-num">Q' + (idx + 1) + '</span>' +
        '<span class="lh-quiz-q-type">' + typeLabel + '</span>' +
      '</div>' +
      '<p class="lh-quiz-q-text">' + sanitizeHtml(q.question_text) + '</p>' +
      hint +
      '<div class="lh-quiz-options">' + renderQuizOptions(q.options, inputType, nameAttr) + '</div>' +
    '</div>';
  }).join('');
}

export function renderQuizResultExplanations(results) {
  return (results || []).map(function(r, idx) {
    var icon = r.isCorrect
      ? '<i class="fas fa-check-circle" style="color:var(--green);"></i>'
      : '<i class="fas fa-times-circle" style="color:var(--red);"></i>';
    var explHtml = '';
    if (!r.isCorrect && r.selectedExplanation) {
      explHtml += '<div class="lh-expl lh-expl-wrong"><strong>Why incorrect:</strong> ' +
        esc(r.selectedExplanation) +
      '</div>';
    }
    if (!r.isCorrect) {
      explHtml += '<div class="lh-expl lh-expl-correct"><strong>Correct answer:</strong> ' +
        esc(r.correctOptionText) +
      '</div>';
    }
    if (r.generalExplanation) {
      explHtml += '<div class="lh-expl lh-expl-general"><strong>Explanation:</strong> ' +
        sanitizeHtml(r.generalExplanation) +
      '</div>';
    }

    return '<div class="lh-result-item">' +
      '<div class="lh-result-header">' +
        icon + ' <strong>Q' + (idx + 1) + ':</strong> ' + sanitizeHtml(r.questionText) +
      '</div>' +
      explHtml +
    '</div>';
  }).join('');
}

function renderQuizOptions(options, inputType, nameAttr) {
  return (options || []).map(function(opt) {
    return '<label class="lh-quiz-option">' +
      '<input type="' + inputType + '" name="' + nameAttr + '" value="' + opt.id + '">' +
      '<span>' + sanitizeHtml(opt.option_text) + '</span>' +
    '</label>';
  }).join('');
}
