{# Partial: Case Display Sets (displaysets) #}
{# Buttons adapt at runtime: if an in-page viewer is present (importAnnotations_main_viewer), #}
{# "View" loads the display set into it; otherwise falls back to the modal viewer. #}
{# An Edit button is shown separately when can_edit is truthy. #}
<div>
    <h5 class="mt-3">Case Display Sets</h5>
    <ul class="list-group">
        {% for ds in case.display_sets.all %}
            <li class="list-group-item" id="displayset-row-{{ ds.pk }}">
                <div class="d-flex align-items-center justify-content-between flex-wrap gap-2">
                    <div>
                        <b>{{ ds.name }}</b>
                        {% if ds.description %}
                            <span class="text-muted ms-1">({{ ds.description }})</span>
                        {% endif %}
                    </div>
                    <div class="d-flex gap-2 flex-shrink-0">
                        {% if ds.viewerstate or ds.annotations %}
                            <button type="button"
                                    class="btn btn-primary btn-sm ds-view-btn"
                                    data-ds-id="{{ ds.pk }}"
                                    data-modal-url="{% url 'atlas:case_displaysets_modal' ds.pk %}"
                                    data-annotations='{{ ds.annotations|safe }}'
                                    data-viewerstate='{{ ds.viewerstate|safe }}'>
                                <i class="bi bi-display"></i> View Display Set
                            </button>
                        {% endif %}
                        <button type="button"
                                class="btn btn-secondary btn-sm view-displayset-modal"
                                data-ds-id="{{ ds.pk }}"
                                data-url="{% url 'atlas:case_displaysets_modal' ds.pk %}">
                            <i class="bi bi-eye"></i> View in Modal
                        </button>
                        {% if can_edit %}
                            <a href="{% url 'atlas:case_displaysets_detail' ds.pk %}?edit=1"
                               class="btn btn-outline-secondary btn-sm">
                                <i class="bi bi-pencil"></i> Edit
                            </a>
                        {% endif %}
                    </div>
                </div>

                <div class="mt-2">
                    <strong>Findings:</strong>
                    {% if ds.findings.all %}
                        <ul class="mb-1">
                            {% for finding in ds.findings.all %}
                                <li>{{ finding.get_link }}</li>
                            {% endfor %}
                        </ul>
                    {% else %}
                        <span class="text-muted">None</span>
                    {% endif %}
                </div>
                <div>
                    <strong>Structures:</strong>
                    {% if ds.structures.all %}
                        <ul class="mb-1">
                            {% for structure in ds.structures.all %}
                                <li>{{ structure.get_link }}</li>
                            {% endfor %}
                        </ul>
                    {% else %}
                        <span class="text-muted">None</span>
                    {% endif %}
                </div>
                <div>
                    <strong>Conditions:</strong>
                    {% if ds.conditions.all %}
                        <ul class="mb-1">
                            {% for condition in ds.conditions.all %}
                                <li>{{ condition.get_link }}</li>
                            {% endfor %}
                        </ul>
                    {% else %}
                        <span class="text-muted">None</span>
                    {% endif %}
                </div>

            </li>
        {% empty %}
            <li class="list-group-item text-muted">
                No display sets for this case.
                {% if can_edit %}
                    <a href="{% url 'atlas:case_displaysets' case.pk %}">Add one now</a>
                {% endif %}
            </li>
        {% endfor %}
    </ul>
</div>

{% include 'atlas/partials/_displayset_modals.html' %}

<script>
    (function () {
        if (!window.__displaysetPartialInitDone) {
            window.__displaysetPartialInitDone = true;

            if (typeof window.mountDisplaysetViewersSafely !== 'function') {
                window.mountDisplaysetViewersSafely = async function () {
                    try {
                        await new Promise(function (resolve) {
                            requestAnimationFrame(function () {
                                requestAnimationFrame(resolve);
                            });
                        });

                        if (typeof window.mountDicomViewersSafely === 'function') {
                            await window.mountDicomViewersSafely();
                        } else if (typeof window.mountDicomViewers === 'function') {
                            window.mountDicomViewers();
                        }

                        requestAnimationFrame(function () {
                            try { window.dispatchEvent(new Event('resize')); } catch (e) {}
                            if (typeof window.resizeDicomViewers === 'function') {
                                try { window.resizeDicomViewers(); } catch (e) {}
                            }
                        });
                    } catch (e) {
                        console.warn('displayset viewer mount failed', e);
                    }
                };
            }

            if (typeof window.loadDisplaysetModal !== 'function') {
                window.loadDisplaysetModal = async function (url, dsId) {
                    if (!url && dsId) url = '/atlas/' + dsId + '/display_sets/modal';
                    if (!url) return;

                    var modalEl = document.getElementById('displaysetModal');
                    var modalBody = document.getElementById('displaysetModalBody');
                    if (!modalEl || !modalBody) return;

                    modalBody.innerHTML = '<p>Loading...</p>';
                    try {
                        var resp = await fetch(url, { credentials: 'same-origin' });
                        var html = await resp.text();
                        modalBody.innerHTML = html;

                        var fsBtn = modalEl.querySelector('.displayset-fullscreen-btn');
                        if (fsBtn) {
                            fsBtn.dataset.url = url;
                            if (dsId) fsBtn.dataset.dsId = dsId;
                        }

                        bootstrap.Modal.getOrCreateInstance(modalEl).show();
                        await window.mountDisplaysetViewersSafely();
                    } catch (error) {
                        console.error('Error loading display set details:', error);
                        modalBody.innerHTML = '<p>Failed to load display set.</p>';
                    }
                };
            }

            if (typeof window.loadDisplaysetFullscreen !== 'function') {
                window.loadDisplaysetFullscreen = async function (url, dsId) {
                    if (!url && dsId) url = '/atlas/' + dsId + '/display_sets/modal';
                    if (!url) return;

                    var leftEl = document.getElementById('displaysetFullscreenLeft');
                    var rightEl = document.getElementById('displaysetFullscreenRight');
                    var fullModalEl = document.getElementById('displaysetFullscreenModal');
                    if (!leftEl || !rightEl || !fullModalEl) return;

                    leftEl.innerHTML = '<p style="color:#fff; padding:1rem;">Loading viewer...</p>';
                    rightEl.innerHTML = '<p>Loading details...</p>';

                    try {
                        var resp = await fetch(url, { credentials: 'same-origin' });
                        var html = await resp.text();
                        var tmp = document.createElement('div');
                        tmp.innerHTML = html;

                        var viewer = tmp.querySelector('.dicom-viewer-root');
                        if (viewer) {
                            leftEl.innerHTML = '';
                            leftEl.appendChild(viewer);
                            try {
                                viewer.style.height = '100%';
                                viewer.style.minHeight = '100%';
                                viewer.style.width = '100%';
                                viewer.style.display = 'block';
                                viewer.style.flex = '1 1 auto';
                            } catch (e) {}
                        } else {
                            leftEl.innerHTML = '<p style="color:#fff; padding:1rem;">No viewer available</p>';
                        }

                        var viewerInTmp = tmp.querySelector('.dicom-viewer-root');
                        if (viewerInTmp) viewerInTmp.remove();
                        rightEl.innerHTML = tmp.innerHTML;

                        bootstrap.Modal.getOrCreateInstance(fullModalEl).show();
                        await window.mountDisplaysetViewersSafely();
                    } catch (error) {
                        console.error('Error loading fullscreen display set:', error);
                        leftEl.innerHTML = '<p style="color:#fff; padding:1rem;">Failed to load viewer</p>';
                        rightEl.innerHTML = '<p>Failed to load details.</p>';
                    }
                };
            }

            document.addEventListener('click', function (e) {
                var modalBtn = e.target.closest('.view-displayset-modal');
                if (modalBtn) {
                    e.preventDefault();
                    var modalUrl = modalBtn.getAttribute('data-url');
                    var modalDsId = modalBtn.getAttribute('data-ds-id');
                    window.loadDisplaysetModal(modalUrl, modalDsId);
                    return;
                }

                var fsBtn = e.target.closest('.displayset-fullscreen-btn');
                if (fsBtn) {
                    e.preventDefault();
                    var fsUrl = fsBtn.dataset.url;
                    var fsDsId = fsBtn.dataset.dsId || null;
                    if (typeof window.loadDisplaysetFullscreen === 'function') {
                        window.loadDisplaysetFullscreen(fsUrl, fsDsId);
                    }
                }
            });
        }

    /**
     * For each "View Display Set" button:
     *  - If the page has an in-page viewer (importAnnotations_main_viewer available),
     *    load the display set's state into it and scroll the viewer into view.
     *  - Otherwise, fall back to the existing modal loader (loadDisplaysetModal).
     */
        document.querySelectorAll('.ds-view-btn').forEach(function (btn) {
            btn.addEventListener('click', function () {
                var dsId = btn.dataset.dsId;
                var modalUrl = btn.dataset.modalUrl;
                var annotations = btn.dataset.annotations;
                var viewerstate = btn.dataset.viewerstate;

                var hasInPageViewer = (
                    typeof window.importAnnotations_main_viewer === 'function' &&
                    typeof window.importViewerState_main_viewer === 'function'
                );

                if (hasInPageViewer) {
                // Ensure viewer UI is visible before applying display set state.
                    var viewerDetails = document.getElementById('dicom-viewer-details');
                    if (viewerDetails && viewerDetails.tagName === 'DETAILS') {
                        viewerDetails.open = true;
                    }

                    try { window.importAnnotations_main_viewer(JSON.parse(annotations || '{}')); } catch (e) { console.warn('displayset annotations import error', e); }
                    try { window.importViewerState_main_viewer(JSON.parse(viewerstate || '{}')); } catch (e) { console.warn('displayset viewerstate import error', e); }

                    try { window.dispatchEvent(new Event('resize')); } catch (e) {}
                    if (typeof window.resizeDicomViewers === 'function') {
                        try { window.resizeDicomViewers(); } catch (e) { console.warn('displayset viewer resize error', e); }
                    }

                // Scroll the viewer into view
                    var viewer = document.getElementById('main_viewer') || document.querySelector('.dicom-viewer-root');
                    if (viewer) { viewer.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); }
                } else if (typeof window.loadDisplaysetModal === 'function') {
                    window.loadDisplaysetModal(modalUrl, dsId);
                } else {
                // Ultimate fallback: navigate to the detail page
                    window.location.href = modalUrl;
                }
            });
        });
    }());
</script>
