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


{% partialdef casedetails-management-links %}

    <div class="btn-toolbar" role="toolbar" aria-label="Case management links">
        {% include 'atlas/partials/casedetails_management_links.html' %}
    </div>

{% endpartialdef %}

{% block content %}

    <div class="container">
        <div class="card mb-4">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-8">
                        <h2 class="card-title mb-2">{{ collection.name }}</h2>

                        {% include 'exam_notes.html' %}
                        {% if casesdetails|length > 20 %}
                            <div id="collection-warning-{{ collection.pk }}" class="alert alert-warning alert-dismissible fade show" role="alert">
                                <strong>Performance warning:</strong> This collection contains {{ casesdetails|length }} cases — in some situations this may adversely affect performance, all features will still work but page loading may be slower. Consider splitting into smaller collections if performance is an issue.
                                <button id="collection-warning-close-{{ collection.pk }}" type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                        {% endif %}

                        <p class="mb-1">
                        </p>

                        <p class="mb-2">
                            {% include "generic/partials/exams/exam_status.html#publish-results" %} {% include "generic/partials/exams/exam_status.html#exam-active" %}
                        </p>

                        <p class="mb-1">
                            Collection type: <span class="badge bg-secondary me-2">{{ collection.get_collection_type_display }}</span>
                            Self review: <span class="badge bg-light text-dark me-2">{{ collection.self_review }}</span>
                            Open access:
                            {% if collection.open_access %}
                                <span class="badge bg-success">Open</span>
                            {% else %}
                                <span class="badge bg-warning text-dark">Restricted</span>
                            {% endif %}
                            Exam mode: <span class="badge bg-info text-dark me-2">{{ collection.exam_mode }}</span>
                        </p>

                        {% if collection.prerequisites.exists %}
                            <div class="mt-3 mb-2">
                                <strong>Prerequisites</strong>
                                <ul class="mb-0">
                                    {% for prereq in collection.prerequisites.all %}
                                        <li><a href="{% url 'atlas:collection_detail' prereq.pk %}">{{ prereq.name }}</a></li>
                                    {% endfor %}
                                </ul>
                            </div>
                        {% endif %}
                    </div>

                    <div class="col-md-4 d-flex flex-column align-items-md-end mt-3 mt-md-0">
                        <div class="mb-2 w-100 text-md-end">
                            {% if collection.collection_type == "VIV" %}
                                <a href="{% url 'atlas:collection_viva' collection.pk %}" class="btn btn-primary mb-2">Start Viva</a>
                                <a href="{% url 'atlas:collection_viva_local' collection.pk %}" class="btn btn-outline-primary mb-2">Start Viva (Local)</a>
                            {% else %}
                                <div class="d-inline-block">
                                    <a class="btn btn-outline-secondary btn-sm" href="{{ collection.get_take_url }}" id="take-url-link">Open</a>
                                    <button
                                        _="on click
                                           writeText(#take-url-link's href) on navigator.clipboard
                                           put 'copied url!' into me
                                           wait 1s
                                           put 'copy link' into me"
                                        class="btn btn-sm btn-outline-secondary ms-1">Copy link</button>
                                </div>
                            {% endif %}
                        </div>

                        {% if collection.prerequisites.exists %}
                            <div class="w-100 text-md-end">
                                <button
                                    title="Sync users from all prerequisite collections into this collection"
                                    hx-post="{% url 'atlas:collection_sync_prerequisite_users' collection.pk %}"
                                    hx-swap="outerHTML"
                                    class="btn btn-sm btn-secondary"
                                >Sync prerequisite users</button>
                            </div>
                        {% endif %}

                        <div class="card border-secondary w-100 mt-3">
                            <div class="card-body py-2 px-3 text-start text-md-end">
                                {% if collection.case_query_messaging_enabled %}
                                    <div class="small text-muted">Outstanding messages</div>
                                    <div class="fw-semibold {% if total_outstanding_messages %}text-danger{% endif %}">
                                        {{ total_outstanding_messages }} pending acknowledgement
                                    </div>
                                    <div class="mt-2 d-flex flex-wrap gap-2 justify-content-md-end">
                                        <a class="btn btn-sm btn-outline-secondary" href="{% url 'atlas:collection_history' collection.pk %}">Open History</a>
                                        <a class="btn btn-sm btn-outline-secondary" href="{% url 'atlas:user_messages_inbox' %}">Global Inbox</a>
                                    </div>

                                    {% if user_message_rows %}
                                        <div class="mt-2 small text-muted">Users</div>
                                        <div class="d-flex flex-column gap-1">
                                            {% for row in user_message_rows|slice:":5" %}
                                                <a class="small {% if row.outstanding_message_count %}text-danger{% endif %}" href="{% url 'atlas:collection_user_messages' collection.pk row.user_user.pk %}">
                                                    {{ row.get_user_name }}
                                                    {% if row.outstanding_message_count %}
                                                        ({{ row.outstanding_message_count }} outstanding)
                                                    {% else %}
                                                        ({{ row.total_review_message_count }} history)
                                                    {% endif %}
                                                </a>
                                            {% endfor %}
                                        </div>
                                    {% endif %}

                                    {% if cid_message_rows %}
                                        <div class="mt-2 small text-muted">CID users</div>
                                        <div class="d-flex flex-column gap-1">
                                            {% for row in cid_message_rows|slice:":5" %}
                                                <a class="small {% if row.outstanding_message_count %}text-danger{% endif %}" href="{% url 'atlas:collection_cid_messages' collection.pk row.cid_user.cid %}">
                                                    {{ row.cid_user }}
                                                    {% if row.outstanding_message_count %}
                                                        ({{ row.outstanding_message_count }} outstanding)
                                                    {% else %}
                                                        ({{ row.total_review_message_count }} history)
                                                    {% endif %}
                                                </a>
                                            {% endfor %}
                                        </div>
                                    {% endif %}
                                {% else %}
                                    <div class="small text-muted">Case query/messaging</div>
                                    <div class="fw-semibold text-muted">Disabled for this collection</div>
                                    <div class="mt-2 d-flex flex-wrap gap-2 justify-content-md-end">
                                        <a class="btn btn-sm btn-outline-secondary" href="{% url 'atlas:collection_history' collection.pk %}">Open History</a>
                                    </div>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-12">
                <h3 class="mb-3">Cases</h3>

                <ol id="full-question-list" class="sortable list-group list-group-numbered">
                    {% for casedetail in casesdetails %}
                        {% include 'atlas/partials/case_list_item.html' %}
                    {% endfor %}
                </ol>
            </div>
        </div>

        {% if can_edit %}
            <div class="row mt-4">
                <div class="col-12 d-flex gap-2">
                    <button id='button-edit-order'
                            title='click and drag questions to change order'
                            data-posturl="{% url 'atlas:exam_json_edit' pk=collection.pk %}"
                            class="btn btn-sm btn-outline-secondary">
                        Edit case order / Remove cases
                    </button>

                    <button id='button-add-case'
                            title='click to add a case to this collection'
                            hx-get="{% url 'atlas:add_case_to_collection' collection.pk %}" hx-swap="innerHTML" hx-target="#case-list"
                            class="btn btn-sm btn-secondary">
                        Add case
                    </button>

                    <div id='case-list'></div>
                </div>
            </div>

            <div class="row mt-3">
                <div class="col-12">
                    <details>
                        <summary>Answer management</summary>

                        <div class="alert alert-danger mt-3">
                            <p class="mb-1">Manage answers for this collection.</p>
                            <small class="text-muted">Please note these are permanent and cannot be undone.</small>
                        </div>

                        <div class="d-flex gap-2">
                            <button title="This will clear all user answers and attempts"
                                    hx-post="{% url 'atlas:collection_reset_answers' collection.pk %}"
                                    hx-swap="outerHTML"
                                    hx-confirm="Are you sure you want to reset all answers? This action cannot be undone."
                                    class="btn btn-danger btn-sm"
                            >Reset all answers</button>

                            <button title="This will specific user answers and attempts"
                                    hx-post="{% url 'atlas:collection_reset_answers_user_list' collection.pk %}"
                                    hx-swap="innerHTML"
                                    hx-target="#user-list"
                                    class="btn btn-warning btn-sm">
                                Reset user answers</button>
                        </div>

                        <div id="user-list" class="mt-3"></div>
                    </details>
                </div>
            </div>
        {% endif %}

        {% include 'exam_overview_js.html' %}
        <!-- Modal for case fields (history / discussion / report) -->
        <div id="case-field-modal" class="modal fade" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-lg modal-dialog-centered">
                <div class="modal-content"></div>
            </div>
        </div>
    </div>


    <script>
        document.addEventListener('DOMContentLoaded', function() {
            try {
                var pk = '{{ collection.pk }}';
                var key = 'collection_warning_dismissed_' + pk;
                var alertEl = document.getElementById('collection-warning-' + pk);
                if (!alertEl) return;
                if (localStorage.getItem(key) === '1') {
                    alertEl.remove();
                    return;
                }
                var btn = document.getElementById('collection-warning-close-' + pk);
                if (btn) {
                    btn.addEventListener('click', function() {
                        try { localStorage.setItem(key, '1'); } catch (e) { /* ignore */ }
                    });
                }
            } catch (e) { console.warn('collection warning persistence error', e); }
        });
    </script>
    <script>
        // Listen for case selection events from a case-search-widget included in this page/modal
        document.body.addEventListener('case:selected', async function(e) {
            try {
                const detail = e.detail || {};
                const casePk = detail.casePk;
                const caseTitle = detail.caseTitle || ('#' + casePk);
                if (!casePk) return;

                if (!window.confirm(`Add case ${caseTitle} to collection {{ collection.name }}?`)) return;

                const url = "{% url 'atlas:add_case_to_collection' collection.pk %}";
                const form = new URLSearchParams();
                form.append('case', casePk);
                const csrfToken = '{{ csrf_token }}';
                const resp = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'X-CSRFToken': csrfToken,
                    },
                    body: form.toString(),
                    credentials: 'same-origin'
                });
                const html = await resp.text();
                // Append the returned case item into the list
                const list = document.getElementById('full-question-list');
                if (list) list.insertAdjacentHTML('beforeend', html);
            } catch (err) {
                console.error('Add case to collection failed', err);
                alert('Failed to add case to collection — check console.');
            }
        });
    </script>
    <script>
        // Global handler for markup links inserted by render_markup
        document.body.addEventListener('click', function(ev){
            var el = ev.target.closest && ev.target.closest('.markup-link');
            if(!el) return;
            ev.preventDefault();
            try{
                var typ = el.getAttribute('data-type');
                var args = el.getAttribute('data-args');
                var href = el.getAttribute('href') || '#';

                if(typ === 'case'){
                    // open case — give option to open in new tab
                    if(window.confirm('Open case in new tab?')){
                        window.open(href, '_blank');
                    } else {
                        window.location = href;
                    }
                    return;
                }

                // For finding/displayset open modal with basic options — endpoints can be wired later
                var modal = document.getElementById('case-field-modal');
                var content = modal && modal.querySelector('.modal-content');
                var parsedArgs = [];
                try{ parsedArgs = JSON.parse(args || '[]'); }catch(e){ parsedArgs = []; }

                if(typ === 'finding'){
                    var findingId = parsedArgs[0] || '';
                    var html = '<div class="modal-header"><h5 class="modal-title">Finding '+findingId+'</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>';
                    html += '<div class="modal-body">';
                    html += '<p>This will open the finding viewer for ID '+findingId+'.</p>';
                    html += '<p><a class="btn btn-sm btn-primary" href="/atlas/finding/'+findingId+'" target="_blank">Open in new tab</a> ';
                    html += '<button class="btn btn-sm btn-secondary" type="button" data-bs-dismiss="modal">Close</button></p>';
                    html += '</div>';
                    if(content) content.innerHTML = html;
                    var bs = new bootstrap.Modal(modal);
                    bs.show();
                    return;
                }

                if(typ === 'displayset'){
                    var caseId = parsedArgs[0] || '';
                    var setName = parsedArgs[1] || '';
                    var html = '<div class="modal-header"><h5 class="modal-title">Display set '+setName+'</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>';
                    html += '<div class="modal-body">';
                    html += '<p>Display set <strong>'+setName+'</strong> from case #'+caseId+'.</p>';
                    html += '<p><a class="btn btn-sm btn-primary" href="/atlas/collection/'+caseId+'" target="_blank">Open case in new tab</a> ';
                    html += '<button class="btn btn-sm btn-secondary" type="button" data-bs-dismiss="modal">Close</button></p>';
                    html += '</div>';
                    if(content) content.innerHTML = html;
                    var bs2 = new bootstrap.Modal(modal);
                    bs2.show();
                    return;
                }

            }catch(err){ console.error('markup link handler error', err); }
        }, false);
    </script>
{% endblock %}
