<div class="exam-question-fragment">
    <form method="POST" class="post-form"
        hx-post="{% if cid %}{% url 'physics:exam_take' pk=exam.pk sk=pos cid=cid passcode=passcode %}{% else %}{% url 'physics:exam_take_user' pk=exam.pk sk=pos %}{% endif %}"
        hx-target="#question-fragment" hx-swap="innerHTML">
        {% csrf_token %}
        {{ form.non_field_errors }}

        <div class="form-contents">
            <!-- Mobile/fragment-visible copy of the question stem (kept hidden on md+ because main page shows it) -->
            <div class="question-stem-fragment d-md-none mb-2">{{ question.stem|safe }}</div>
            <ol class="physics-answer-list">
                <li data-ans="a">
                    <div class="fieldWrapper flex-container">
                        {{ form.a.errors }}
                        <label for="{{ form.a.id_for_label }}" class="flex-8 question-text">{{ question.a|safe }}</label>
                        <span class="flex-1">{{ form.a }}<span class="postinput"></span></span>
                    </div>
                    {% if exam.publish_results and question.a_feedback %}
                        <span class="feedback">Feedback: {{ question.a_feedback }}</span>
                    {% endif %}
                </li>

                <li data-ans="b">
                    <div class="fieldWrapper flex-container">
                        {{ form.b.errors }}
                        <label for="{{ form.b.id_for_label }}" class="flex-8 question-text">{{ question.b|safe }}</label>
                        <span class="flex-1">{{ form.b }}<span class="postinput"></span></span>
                    </div>
                </li>

                <li data-ans="c">
                    <div class="fieldWrapper flex-container">
                        {{ form.c.errors }}
                        <label for="{{ form.c.id_for_label }}" class="flex-8 question-text">{{ question.c|safe }}</label>
                        <span class="flex-1">{{ form.c }}<span class="postinput"></span></span>
                    </div>
                </li>

                <li data-ans="d">
                    <div class="fieldWrapper flex-container">
                        {{ form.d.errors }}
                        <label for="{{ form.d.id_for_label }}" class="flex-8 question-text">{{ question.d|safe }}</label>
                        <span class="flex-1">{{ form.d }}<span class="postinput"></span></span>
                    </div>
                </li>

                <li data-ans="e">
                    <div class="fieldWrapper flex-container">
                        {{ form.e.errors }}
                        <label for="{{ form.e.id_for_label }}" class="flex-8 question-text">{{ question.e|safe }}</label>
                        <span class="flex-1">{{ form.e }}<span class="postinput"></span></span>
                    </div>
                </li>
            </ol>
        </div>

        <div class="mt-2">
            {% if previous > -1 %}
                <button type="submit" name="previous" class="save btn btn-secondary" title="Click to save your answer(s) and go to the previous question">Previous</button>
            {% endif %}

            {% if next %}
                <button type="submit" name="next" class="save btn btn-secondary" title="Click to save your answer(s) and go to the next question">Next</button>
            {% else %}
                {% if not exam.publish_results %}
                    <button type="submit" name="save" class="save btn btn-default" title="Click to save your current answer(s)">Save</button>
                {% endif %}
            {% endif %}

            <br />
            <button type="submit" id="overview-button" name="finish" class="save btn btn-default" title="Click to go to the overview page (your answers will be saved).">Overview</button>
            <button type="submit" id="goto-button" value="test" name="goto" class="hide">goto</button>
        </div>
    </form>

    <script>
        (function () {
            /* run after fragment is loaded */
            // Update the global page header question number and stem so the top of the page stays in sync
            try {
                var qnum = document.getElementById('question-number');
                if (qnum) { qnum.textContent = '{{ pos|add:"1" }}'; }
                var qstem = document.getElementById('question-stem');
                if (qstem) { qstem.innerHTML = '{{ question.stem|escapejs }}'; }
            } catch (err) {
                console.warn('Could not update global question header from fragment', err);
            }
            {% if not exam.publish_results and not cid_user_exam.completed %}
                let time_limit = '{{ exam.time_limit }}';
                if (time_limit != 'None') {
                    let end_time = new Date({{ cid_user_exam.start_time|date:"U" }} * 1000 + parseInt('{{ exam.time_limit }}') * 1000);
                    if (typeof initializeClock === 'function') {
                        initializeClock('clockdiv', end_time);
                    }
                }

            {% elif exam.publish_results %}
                $('ol.physics-answer-list input').each((n, el) => { el.disabled = true; });
                {{ question.get_answers_js }}.forEach((el, n) => {
                    const li_el = $(`ol.physics-answer-list li:eq(${n})`);

                    if (el) {
                        li_el.addClass('answer-true');
                    } else {
                        li_el.addClass('answer-false');
                    }

                    if (el == li_el.find('input').get(0).checked) {
                        li_el.addClass('answer-correct');
                    } else {
                       li_el.addClass('answer-incorrect');
                    }
                });

            {% elif cid_user_exam.completed %}
                $('ol.physics-answer-list input').each((n, el) => { el.disabled = true; });
            {% endif %}

            // build the question menu locally so it is available after fragment swaps
            $('#menu-list').empty();
            for (let i = 0; i < {{ exam_length }}; i++) {
                const qbutton = $(`<button class="question-menu-item" name="goto-${i}" data-qn="${i}">${i+1}</button>`);
                if (i == {{ pos }}) { qbutton.addClass('current-question'); }
                $('#menu-list').append(qbutton);
            }

            $('button.question-menu-item').on('click', (e) => {
                document.getElementById('goto-button').value = e.currentTarget.dataset.qn;
                $('#goto-button').click();
            });
        })();
    </script>
</div>
