<div class="sba-question-fragment">
    <form method="POST" class="post-form"
          hx-post="{% if cid %}{% url 'sbas:exam_take' pk=exam.pk sk=pos cid=cid passcode=passcode %}{% else %}{% url 'sbas:exam_take_user' pk=exam.pk sk=pos %}{% endif %}"
          hx-target="#question-fragment" hx-swap="innerHTML">
        {% csrf_token %}
        <div class="form-contents-visible">
            <div class="question-stem-fragment d-md-none mb-2">{{ question.stem|safe }}</div>
            <ul class="sba-answer-list list-group">
                <li class="list-group-item" data-ans="a" role="button" tabindex="0" aria-pressed="false">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>{{ question.a_answer|safe }}</div>
                    </div>
                </li>
                <li class="list-group-item" data-ans="b" role="button" tabindex="0" aria-pressed="false">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>{{ question.b_answer|safe }}</div>
                        <div></div>
                    </div>
                </li>
                <li class="list-group-item" data-ans="c" role="button" tabindex="0" aria-pressed="false">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>{{ question.c_answer|safe }}</div>
                        <div></div>
                    </div>
                </li>
                <li class="list-group-item" data-ans="d" role="button" tabindex="0" aria-pressed="false">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>{{ question.d_answer|safe }}</div>
                        <div></div>
                    </div>
                </li>
                <li class="list-group-item" data-ans="e" role="button" tabindex="0" aria-pressed="false">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>{{ question.e_answer|safe }}</div>
                        <div></div>
                    </div>
                </li>
            </ul>
            {# Hidden form field to track selected choice for SBA question #}
            <input type="hidden" name="answer" id="id_answer" value="{{ saved_answer|default_if_none:'' }}" />
        </div>

        <div class="mt-2">
            <div class="d-flex align-items-center justify-content-between">
                <div class="btn-row">
                    {% if previous > -1 %}
                        <button type="submit" name="previous" class="btn btn-outline-secondary" title="Save and go to previous">Previous</button>
                    {% endif %}

                    {% if next %}
                        <button type="submit" name="next" class="btn btn-primary">Next</button>
                    {% else %}
                        {% if not exam.publish_results %}
                            <button type="submit" name="save" class="btn btn-success">Save</button>
                        {% endif %}
                    {% endif %}

                    <br />
                    <button type="submit" name="finish" class="btn btn-outline-primary ms-0 ms-sm-2 mt-2 mt-sm-0">Overview</button>
                    <button type="submit" id="goto-button" value="test" name="goto" class="visually-hidden">goto</button>
                </div>

                <div class="flag-container ms-3">
                    {% include 'sbas/partials/exam_flag_button.html' %}
                </div>
            </div>
        </div>
    </form>

    <script>
        (function () {
            try {
                // expose current question index for global listeners
                window.currentQuestionPos = {{ pos }};
                // Update the fragment mobile stem copy
                var qstem = document.getElementById('question-stem');
                if (qstem) { qstem.innerHTML = '{{ question.stem|escapejs }}'; }

                // build the question menu locally so it is available after fragment swaps
                $('#menu-buttons').empty();
                const serverAnswered = {{ answered_json|default:'null'|safe }};
                const serverFlagged = {{ flagged_json|default:'null'|safe }};
                if (Array.isArray(serverAnswered)) window.examQuestionAnswered = serverAnswered;
                if (Array.isArray(serverFlagged)) window.examQuestionFlagged = serverFlagged;
                for (let i = 0; i < {{ exam_length }}; i++) {
                    const qbutton = $(`<button type="button" class="btn btn-sm btn-outline-secondary question-menu-item" name="goto-${i}" data-qn="${i}">${i+1}</button>`);
                    if (i == {{ pos }}) { qbutton.addClass('current-question'); }
                    if (window.examQuestionAnswered && window.examQuestionAnswered[i]) qbutton.addClass('answered');
                    if (window.examQuestionFlagged && window.examQuestionFlagged[i]) qbutton.addClass('flagged');
                    $('#menu-buttons').append(qbutton);
                }
                if(typeof window.updateQuestionMenu === 'function') window.updateQuestionMenu();
            } catch (e) { console && console.error && console.error(e); }

            // Make SBA choices clickable and auto-save via HTMX
            try {
                // mark saved answer as selected
                const saved = '{{ saved_answer|default_if_none:"" }}';
                if (saved) {
                    const sel = document.querySelector(`ul.sba-answer-list li[data-ans="${saved}"]`);
                    if (sel) sel.classList.add('selected');
                }

                // find csrf token
                const csrfEl = document.querySelector('input[name="csrfmiddlewaretoken"]');
                const csrftoken = csrfEl ? csrfEl.value : null;

                // attach click handler (idempotent)
                document.querySelectorAll('ul.sba-answer-list li').forEach(li => {
                    if (li.dataset.delegateBound) return;
                    li.dataset.delegateBound = '1';
                    const activate = (el) => {
                        const choice = el.dataset.ans;
                            // update hidden input and visuals
                        const hidden = document.getElementById('id_answer');
                        if (hidden) hidden.value = choice;
                        document.querySelectorAll('ul.sba-answer-list li').forEach(x=>{ x.classList.remove('selected'); x.setAttribute('aria-pressed','false'); });
                        el.classList.add('selected'); el.setAttribute('aria-pressed','true');

                        // Note: do not mark answered here — wait for server 'saved' confirmation

                            // auto-save via HTMX if available and exam isn't in review/completed mode
                        if (window.htmx && typeof htmx.ajax === 'function'){
                            const form = el.closest('form.post-form');
                            const postUrl = form ? (form.getAttribute('hx-post') || form.getAttribute('action')) : null;
                            if (postUrl){
                                const values = { 'answer': choice, 'save': '' };
                                const headers = {};
                                if (csrftoken) headers['X-CSRFToken'] = csrftoken;
                                htmx.ajax('POST', postUrl, { target: '#question-fragment', swap: 'innerHTML', values: values, headers: headers });
                            }
                        } else {
                                // fallback: submit the form normally
                            const form = el.closest('form.post-form');
                            if (form){
                                const tmp = document.createElement('input'); tmp.type='hidden'; tmp.name='save'; tmp.value=''; form.appendChild(tmp);
                                form.submit();
                            }
                        }
                    };

                    li.addEventListener('click', function(e){ try{ activate(this);}catch(ex){ console && console.error && console.error(ex); } });
                    li.addEventListener('keydown', function(e){ if(e.key === 'Enter' || e.key === ' ') { e.preventDefault(); try{ activate(this);}catch(ex){ console && console.error && console.error(ex);} } });
                });
            } catch(e){ console && console.error && console.error(e); }
        })();
    </script>
</div>
