{% extends 'rapids/exams.html' %}

{% block content %}
  <div class="row">
    <div class="col-md-6" id="main-col">
      <div class="card mb-3 bg-dark text-light border-secondary">
        <div class="card-body">
          <div class="d-flex justify-content-between align-items-start">
            <div>
              <h5 class="card-title mb-1">Marking question {{ question_details.current }} of {{ question_details.total }}</h5>
              <div class="mb-2">
                <a class="btn btn-sm btn-outline-secondary me-1" href="{% url 'rapids:question_detail' question.id %}" title="View the Question">View</a>
                <a class="btn btn-sm btn-outline-secondary me-1" href="{% url 'rapids:rapid_update' question.id %}" title="Edit the Question">Edit</a>
                {% if request.user.is_superuser %}
                  <a class="btn btn-sm btn-outline-secondary me-1" href="{% url 'admin:rapids_rapid_change' question.id %}" title="Admin Edit">Admin Edit</a>
                {% endif %}
                <a class="btn btn-sm btn-outline-secondary" href="{% url 'rapids:mark' exam.id question_number %}">Classic mark</a>
              </div>
              <h6 class="mb-1 text-info">{% if question.normal %}Normal film{% else %}Abnormal film{% endif %}</h6>
              {% if not question.normal %}
                <div class="small text-muted">Region: {{ question.get_regions }} | Abnormalities: {{ question.get_abnormalities }}</div>
                <div class="mt-2">Primary answer: <span id="primary-answer" class="text-warning fw-semibold" title="The primary answer of the question">{{ question.get_primary_answer }}</span></div>
              {% endif %}
            </div>
            <div class="text-end">
              <button class="btn btn-sm btn-outline-primary" type="button" id="toggle-images">Toggle images</button>
            </div>
          </div>

          <div class="mt-3">
            <form method="POST" class="post-form">{% csrf_token %}
              <p class="small text-muted">Click each answer to toggle through marks awarded (as per colour). This UI writes marks immediately.</p>
              <div class="d-flex justify-content-between align-items-center mb-2">
                <div></div>
                <div>
                  {% if question_details.current > 1 %}
                    <button type="submit" name="previous" class="btn btn-outline-secondary btn-sm me-1">Previous</button>
                  {% endif %}
                  <button type="submit" name="save" class="btn btn-primary btn-sm me-1">Save</button>
                  {% if question_details.current < question_details.total %}
                    <button type="submit" name="next" class="btn btn-outline-primary btn-sm me-1">Next</button>
                  {% endif %}
                </div>
              </div>
              <div class="mb-2">
                <button class="btn btn-sm btn-outline-info me-1" hx-get="{% url 'rapids:mark2_exam_marked' exam.id question_number %}" hx-target="#exam-marked-container" hx-swap="innerHTML">Show exam-submitted answers</button>
                <button class="btn btn-sm btn-outline-info" hx-get="{% url 'rapids:mark2_question_marked' question.pk %}" hx-target="#question-marked-container" hx-swap="innerHTML">Show all stored answers for question</button>
              </div>

              <div class="row">
                <div class="col-12">
                  <h6 class="mb-2">Answers</h6>
                  <ul id="answer-list" class="list-group answer-list mb-3">
                    {% include 'rapids/partials/_mark2_marked_list_fragment.html' %}
                    {% include 'rapids/partials/_mark2_unmarked_list_fragment.html' %}
                  </ul>
                  <div id="exam-marked-container" class="mt-2"></div>
                  <div id="question-marked-container" class="mt-2"></div>
                </div>
              </div>

              <div class="mt-3">
                <div class="small text-muted key">Key: <span class="key-item correct text-success fw-semibold">2 Marks</span>, <span class="key-item half-correct text-warning fw-semibold">1 Mark</span>, <span class="key-item incorrect text-danger fw-semibold">0 Marks</span></div>
              </div>

              <span class="visually-hidden">{{ form.as_p }}</span>
            </form>
          </div>
        </div>
      </div>
    </div>

    <div class="col-md-6" id="dicom-col">
      <div id="single-dicom-viewer" class="marking-dicom" data-images="{{ question.get_image_url_array }}" data-annotations='{{ question.get_image_annotations }}'></div>
    </div>
  </div>
{% endblock %}

{% block css %}
  <style>
    .answer { cursor: pointer; }
    .answer.correct { color: #2a9d3f !important; background-color: transparent; }
    .answer.half-correct { color: #ffb020 !important; background-color: transparent; }
    .answer.incorrect { color: #d3413a !important; background-color: transparent; }
    .answer.not-marked { color: inherit; background-color: transparent; }
    .answer-list .list-group-item pre { margin: 0; font-family: monospace; white-space: pre-wrap; }
    .mark-controls { display:flex; gap:0.25rem; }
    .mark-btn { padding: 0.15rem 0.4rem; font-size: 0.8rem; }
    
    .marked-correct { border-left: 4px solid #2a9d3f; }
    .marked-half-correct { border-left: 4px solid #ffb020; }
    .marked-incorrect { border-left: 4px solid #d3413a; }

    .key .key-item { display:inline-block; padding-left:8px; margin-left:6px; }
    .key .key-item.correct { border-left: 8px solid #2a9d3f; }
    .key .key-item.half-correct { border-left: 8px solid #ffb020; }
    .key .key-item.incorrect { border-left: 8px solid #d3413a; }
    .answer-actions { min-width: 6rem; }
    .answer-actions .action-icon { margin-left: 0.5rem; }
    .answer-actions .copy-to-clipboard { cursor: pointer; }
    .mark-btn.active { background-color: #0d6efd; color: #fff; border-color: #0d6efd; }
  </style>
{% endblock %}

{% block js %}
  <script>
    (function(){
      function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
          const cookies = document.cookie.split(';');
          for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
              cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
              break;
            }
          }
        }
        return cookieValue;
      }
      const csrftoken = getCookie('csrftoken');

      // Delegated click handler for answers
      document.addEventListener('click', function(e){
        if (e.target.closest('.answer-actions') || e.target.closest('.mark-controls') || e.target.closest('.copy-to-clipboard')) return;

        let spanEl = e.target.closest('span.answer');
        if (!spanEl) {
          const li = e.target.closest('#answer-list li');
          if (!li) return;
          spanEl = li.querySelector('span.answer');
          if (!spanEl) return;
        }

        if (!spanEl.classList.contains('correct') && !spanEl.classList.contains('half-correct') && !spanEl.classList.contains('incorrect') && !spanEl.classList.contains('not-marked')) {
          spanEl.classList.add('not-marked');
        }

        const states = ['not-marked', 'correct', 'half-correct', 'incorrect'];
        let currentState = 'not-marked';
        for (let p of spanEl.classList) {
          if (states.includes(p)) { currentState = p; break; }
        }
        let idx = (states.indexOf(currentState) + 1) % states.length;
        const newState = states[idx];

        let numeric = null;
        if (newState === 'correct') numeric = 2;
        else if (newState === 'half-correct') numeric = 1;
        else if (newState === 'incorrect') numeric = 0;

        setMarkForSpan(spanEl, numeric);
      }, false);

      function updateMarkedAnswersField() {
        const marked = { 'correct': [], 'half-correct': [], 'incorrect': [] };
        document.querySelectorAll('#answer-list span.answer').forEach(function(el) {
          if (el.classList.contains('correct')) marked.correct.push((el.title || el.textContent).trim());
          else if (el.classList.contains('half-correct')) marked['half-correct'].push((el.title || el.textContent).trim());
          else if (el.classList.contains('incorrect')) marked.incorrect.push((el.title || el.textContent).trim());
        });

        let hidden = document.getElementById('id_marked_answers');
        if (!hidden) {
          hidden = document.createElement('input');
          hidden.type = 'hidden';
          hidden.name = 'marked_answers';
          hidden.id = 'id_marked_answers';
          const form = document.querySelector('form.post-form');
          if (form) form.appendChild(hidden);
        }
        hidden.value = JSON.stringify(marked);
      }

      function attachNumericControls() {
        function makeButton(label, cls) {
          const b = document.createElement('button');
          b.type = 'button';
          b.className = 'btn btn-sm btn-outline-secondary me-1 mark-btn ' + cls;
          b.textContent = label;
          return b;
        }

        document.querySelectorAll('.answer-list li').forEach(function(li) {
          if (li.querySelector('.mark-controls')) return;
          const span = li.querySelector('span.answer');
          if (!span) return;
          if (!span.classList.contains('correct') && !span.classList.contains('half-correct') && !span.classList.contains('incorrect') && !span.classList.contains('not-marked')) {
            span.classList.add('not-marked');
          }
          const controls = document.createElement('div');
          controls.className = 'mark-controls mt-2';
          const b2 = makeButton('2', 'mark-2');
          const b1 = makeButton('1', 'mark-1');
          const b0 = makeButton('0', 'mark-0');
          const bClear = makeButton('⨯', 'mark-clear');

          controls.appendChild(b2);
          controls.appendChild(b1);
          controls.appendChild(b0);
          controls.appendChild(bClear);
          li.appendChild(controls);

          b2.addEventListener('click', function(){ setMarkForSpan(span, 2); });
          b1.addEventListener('click', function(){ setMarkForSpan(span, 1); });
          b0.addEventListener('click', function(){ setMarkForSpan(span, 0); });
          bClear.addEventListener('click', function(){ setMarkForSpan(span, null); });

          (function(){
            let state = null;
            if (span.classList.contains('correct')) state = 2;
            else if (span.classList.contains('half-correct')) state = 1;
            else if (span.classList.contains('incorrect')) state = 0;
            [b2, b1, b0, bClear].forEach(b => b.classList.remove('active'));
            if (state === 2) b2.classList.add('active');
            else if (state === 1) b1.classList.add('active');
            else if (state === 0) b0.classList.add('active');
            else bClear.classList.add('active');
          })();
        });
      }

      function setMarkForSpan(el, numeric) {
        const li = el.closest('li');
        let state = 'not-marked';
        if (numeric === 2) state = 'correct';
        else if (numeric === 1) state = 'half-correct';
        else if (numeric === 0) state = 'incorrect';
        el.className = 'answer ' + state;
        if (li) {
          li.classList.remove('marked-correct','marked-half-correct','marked-incorrect','marked-item');
          if (state === 'correct') {
            li.classList.add('marked-item','marked-correct');
          } else if (state === 'half-correct') {
            li.classList.add('marked-item','marked-half-correct');
          } else if (state === 'incorrect') {
            li.classList.add('marked-item','marked-incorrect');
          }
        }
        try {
          if (li) {
            const btn2 = li.querySelector('.mark-2');
            const btn1 = li.querySelector('.mark-1');
            const btn0 = li.querySelector('.mark-0');
            const btnClear = li.querySelector('.mark-clear');
            [btn2, btn1, btn0, btnClear].forEach(b => { if (b) { b.classList.remove('active'); } });
            if (numeric === 2 && btn2) btn2.classList.add('active');
            else if (numeric === 1 && btn1) btn1.classList.add('active');
            else if (numeric === 0 && btn0) btn0.classList.add('active');
            else if (numeric === null && btnClear) btnClear.classList.add('active');
          }
        } catch (err) {}

        updateMarkedAnswersField();
      }

      function initMark2() {
        attachNumericControls();
      }

      if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initMark2);
      } else {
        initMark2();
      }

      document.addEventListener('htmx:afterSwap', function(evt) {
        initMark2();
      });

      const postForm = document.querySelector('form.post-form');
      if (postForm) {
        postForm.addEventListener('submit', function(e){
          try { updateMarkedAnswersField(); } catch (err) {}
        });
      }

      document.addEventListener('click', function(e){
        const btn = e.target.closest('.copy-to-clipboard');
        if (!btn) return;
        const text = btn.getAttribute('data-text');
        if (!text) return;
        try {
          navigator.clipboard.writeText(text);
          const prev = btn.textContent;
          btn.textContent = 'Copied';
          setTimeout(function(){ btn.textContent = prev; }, 1200);
        } catch (err) {
          console.warn('copy failed', err);
        }
      });

      // Toggle images handler matching classic mode
      const toggleBtn = document.getElementById("toggle-images");
      if (toggleBtn) {
        toggleBtn.addEventListener('click', function() {
          const dicomCol = document.getElementById("dicom-col");
          const mainCol = document.getElementById("main-col");
          if (dicomCol && mainCol) {
            if (dicomCol.style.display === "none") {
              dicomCol.style.display = "";
              mainCol.className = "col-md-6";
            } else {
              dicomCol.style.display = "none";
              mainCol.className = "col-md-12";
            }
          }
        });
      }

    })();
  </script>
{% endblock %}
