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

{% block content %}


    {% include 'atlas/question_link_header.html' %}

    <h2>Display Sets: {{ case.title }}</h2>

    <details class="help-text">
        <summary><i class="bi bi-info-circle"></i> Help</summary>
        <p>This page shows the display sets associated with the case.</p>
        <p>If you have access you can add and edit display sets.</p>
    </details>


    <div id="main_viewer" class="dicom-viewer-root"
         style="box-sizing: border-box; background: #222; width: 100%; height: 600px;"
         data-auto-cache-stack="false"
         data-images='{{case.get_series_images_nested}}'
    ></div>

    <div class="mb-3">
        <button hx-get="{% url 'atlas:case_displaysets_add' case.pk %}" hx-target="#displayset-add-form" hx-swap="innerHTML">Add Display Set</button>
        <div id="displayset-add-form"></div>
    </div>

    <ul class="list-group mb-4" id="display-set-list">
        {% for ds in case.display_sets.all %}
            {% include 'atlas/partials/displayset_row.html' %}
        {% empty %}
            <li class="list-group-item text-muted">No display sets for this case.</li>
        {% endfor %}
    </ul>

{% endblock %}

{% block js %}
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            // Helper: wait for mount function and mount the viewers safely
            function waitForMountFn(timeout = 5000) {
                if (window.mountDicomViewers) return Promise.resolve(window.mountDicomViewers);
                return new Promise((resolve, reject) => {
                    const start = Date.now();
                    function poll() {
                        if (window.mountDicomViewers) return resolve(window.mountDicomViewers);
                        if (Date.now() - start > timeout) return reject(new Error('mountDicomViewers not available'));
                        requestAnimationFrame(poll);
                    }
                    poll();
                });
            }

            async function mountDicomViewersSafely(timeout = 5000) {
                try {
                    await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
                    const mountFn = await waitForMountFn(timeout);
                    try { mountFn(); } catch (e) { console.warn('mountDicomViewers failed', e); }
                    requestAnimationFrame(() => { try { window.dispatchEvent(new Event('resize')); } catch (e) {} });
                } catch (err) {
                    console.warn('Viewer initialization deferred/fallback:', err);
                }
            }

            // Initialize viewers deterministically
            mountDicomViewersSafely();


            {% if selected_displayset %}
                (async function(){
                    try {
                        await mountDicomViewersSafely();
                        importAnnotations_main_viewer({{ selected_displayset.annotations|safe }});
                        importViewerState_main_viewer({{ selected_displayset.viewerstate|safe }});
                        // Highlight the selected displayset row
                        var selectedRow = document.getElementById("displayset-{{ selected_displayset.pk }}");
                        if (selectedRow) {
                            selectedRow.style.border = "2px solid #ffc107";
                        }
                    } catch (e) { console.warn('failed to import selected displayset state', e); }
                })();

                {% if edit %}
                    var editButton = document.getElementById("displayset-{{ selected_displayset.pk }}-edit-btn");
                    if (editButton) {
                        editButton.click();
                    }

                {% endif %}
            {% endif %}


        });
        document.addEventListener("htmx:beforeRequest", function(evt) {
            console.log("htmx:beforeRequest", evt.detail);
    // Only for the display set add form
            var form = evt.target;
            console.log("Form:", form);
            console.log("Form matches:", form.matches("form[hx-post*='{% url 'atlas:case_displaysets_add' case.pk %}']"));
            console.log("Form matches:", form.matches("form[hx-post*='display_sets/edit']"));
            if (form && (form.matches("form[hx-post*='{% url 'atlas:case_displaysets_add' case.pk %}']") ||form.matches("form[hx-post*='display_sets/edit']" ))) {
        // Set hidden fields from JS functions
                var viewerState = window.exportViewerState_main_viewer ? window.exportViewerState_main_viewer() : "{}";
                var annotations = window.exportAnnotations_main_viewer ? window.exportAnnotations_main_viewer() : "{}";
                evt.detail.requestConfig.parameters["annotations"] = annotations;
                evt.detail.requestConfig.parameters["viewerstate"] = viewerState;
                console.log(evt)
            }
        });
    </script>

{% endblock %}
