{% extends 'base.html' %}
{% load help_tags %}

{% block content %}
    <div class="container anatomy my-3">
        {% include 'user_score_header.html' %}
        <div class="row">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-body p-0">
                        <div class="p-2 d-flex align-items-center justify-content-between">
                            <div class="small text-muted">Filter questions by marks</div>
                            <div>
                                <select id="filter-score" class="form-select form-select-sm" style="min-width:120px;">
                                    <option value="all">All scores</option>
                                    <option value="2">2 (full)</option>
                                    <option value="1">1</option>
                                    <option value="0">0</option>
                                </select>
                            </div>
                        </div>
                        <ul class="list-group list-group-flush score-answer-list">
                            {% for ans, score, correct_answer in answers_and_marks %}
                                <li class="list-group-item d-flex justify-content-between align-items-start" data-score="{{ score }}">
                                    <div class="d-flex align-items-start">
                                        <div class="me-3">
                                            <span class="badge bg-secondary">{{ forloop.counter }}</span>
                                        </div>
                                        <div>
                                            <div class="fw-semibold">Question {{ forloop.counter }}</div>
                                            <div class="small text-muted">Correct answer: {% if exam.publish_results %}<span class="correct-answer">{{ correct_answer }}</span>{% else %}—{% endif %}</div>
                                            <div class="mt-2"><pre class="mb-0">{{ ans }}</pre></div>
                                            {% if exam.publish_results or view_all_results %}
                                                <div class="small mt-2">
                                                    Marks:
                                                    {% if score == 2 %}
                                                        <span class="badge bg-success ms-1">{{ score }}</span>
                                                    {% elif score == 1 %}
                                                        <span class="badge bg-warning text-dark ms-1">{{ score }}</span>
                                                    {% else %}
                                                        <span class="badge bg-secondary ms-1">{{ score }}</span>
                                                    {% endif %}
                                                </div>
                                            {% endif %}
                                        </div>
                                    </div>
                                    <div class="text-end ms-3">
                                        {% if exam.publish_results %}
                                            <button type="button" class="btn btn-sm btn-outline-primary view-question-button" data-qn={{forloop.counter0}}>View</button>
                                        {% else %}
                                            <button type="button" class="btn btn-sm btn-outline-secondary" disabled>View</button>
                                        {% endif %}
                                        {% if request.user.is_staff %}
                                            <button type="button" class="btn btn-sm btn-outline-secondary ms-2 admin-edit-button" data-qn="{{ forloop.counter0 }}">Edit</button>
                                        {% endif %}
                                        {% if request.user.is_staff or view_all_results or request.user in exam.author.all %}
                                            {% with q=questions|get_item:forloop.counter0 %}
                                                {% with ua=user_answers_map|get_item:q.pk %}
                                                    {% if ua %}
                                                        <a href="{% url 'generic:view_answer_history' app_name='anatomy' model_name='UserAnswer' pk=ua.pk %}" class="btn btn-sm btn-outline-info ms-2">History</a>
                                                    {% endif %}
                                                {% endwith %}
                                            {% endwith %}
                                        {% endif %}
                                    </div>
                                </li>
                            {% endfor %}
                        </ul>
                    </div>
                </div>

                {% include 'user_scores_footer.html' %}
            </div>

            <div class="col-md-4">
                {% if exam.publish_results %}
                    <div class="card sticky-top" style="top:1rem;">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h6 class="mb-0">Viewer</h6>
                            <button class="btn btn-sm btn-outline-secondary" id="hide-viewer">Hide</button>
                        </div>
                        <div class="card-body p-0">
                            <div class="viewer-block">
                                <div class="viewer-body overflow-auto p-3" style="max-height: calc(100vh - 160px);">
                                    <div>Question <span class="question-number">No question loaded</span></div>
                                    <div id="question-title" class="fw-bold my-2"></div>
                                    <div id="question-question" class="mb-2"></div>
                                    <div id="single-dicom-viewer" class="dicom-viewer mb-2" data-images="" data-annotations=''></div>
                                    <div class="small text-muted">Answers:</div>
                                    <div class="answers mt-1"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                {% endif %}
            </div>
        </div>
    </div>
{% endblock %}
{% block css %}
    <style>
        /* Ensure the sticky viewer stays within its column and the canvas scales */
        .anatomy .card.sticky-top { max-width: 100%; }
        /* Keep viewer usable by enforcing a minimum width on larger viewports */
        @media (min-width: 768px) {
            .anatomy .card.sticky-top { min-width: 600px; }
        }
        .anatomy .viewer-block .viewer-body { overflow: auto; }
        .viewer-block .answers { background: #f8f9fa; padding: .5rem; border-radius: .25rem; color: #212529; }
        .viewer-block .answers, .viewer-block .answers * { color: #212529 !important; }
        .viewer-block .answers pre { margin: 0; white-space: pre-wrap; }
        .dicom-viewer, .dicom-viewer .canvas-panel, .dicom-viewer .cornerstone-element { max-width: 100%; box-sizing: border-box; }
        .dicom-viewer canvas { max-width: 100% !important; width: 100% !important; height: auto !important; display: block; }
        #single-dicom-viewer { width: 100%; }
        /* hide horizontal overflow from the card body so the page doesn't scroll sideways */
        .anatomy .card .card-body { overflow-x: hidden; }
    </style>
{% endblock %}
{% block js %}
    {% if exam.publish_results %}
        <script>
            $(document).ready(function () {
                $("#hide-viewer").on('click', function(){ $('.viewer-block .viewer-body').toggle(); });

                // Filter questions by score using Bootstrap's d-none for consistent layout
                $("#filter-score").on('change', function(){
                    const val = $(this).val();
                    $(".list-group-item[data-score]").each(function(){
                        const s = $(this).data('score');
                        if(val === 'all' || String(s) === String(val)) $(this).removeClass('d-none'); else $(this).addClass('d-none');
                    });
                });

                $(".view-question-button").on("click", function (e) {
                    question_number = e.currentTarget.dataset.qn;
                    $("#single-dicom-viewer").empty();
                    $.ajax({
                        url: `{% url 'anatomy:question_review' pk=exam.pk %}`,
                        data: {
                            csrfmiddlewaretoken: "{{ csrf_token }}",
                            question_number: question_number
                        },
                        type: "POST",
                        dataType: "json",
                    })
                        .done(function (data) {
                            let event = new CustomEvent('loadDicomViewerUrls', { "detail": { "images": data.images, "annotations": data.annotations } });
                            window.dispatchEvent(event);
                            $(".viewer-block .answers").empty().append(data.answers.toString());
                            $("#question-title").empty().append(data.title);
                            $("#question-question").empty().append(data.question);
                            n = parseInt(question_number) + 1
                            $(".viewer-block .question-number").empty().append(n);
                            $(".viewer-block .viewer-body").show();
                        })
                        .always(function () { console.log('[Done]'); });
                });

            // auto-click first view button to populate viewer
                const firstView = $(".view-question-button:visible").first();
                if(firstView.length){ firstView.click(); }
            });
        </script>
    {% endif %}
{% endblock %}
