{% load partials %}

{% partialdef case-series %}
    {% for series in case.get_ordered_series %}
        <span class="series-block" id="series-block-{{ series.pk }}">
            <span>
                <span class="series-block-series-number">Series {{ forloop.counter }}:</span><br>
                <a href="{% url 'atlas:series_detail' pk=series.pk %}">
                    {{series.get_block}}
                </a>
                <br>
                <button type="button"
                        class="btn btn-outline-primary btn-sm select-series-btn"
                        style="display: none;"
                        data-series-id="{{series.pk}}">
                    Select
                </button>
                <input type="checkbox" class="hide" name="series-ids" value="{{series.pk}}">
                <span class="series-block-popup-link">
                    <a href="#"
                       onclick="return window.create_popup_window('/atlas/series/{{series.pk}}', 'Series')">Popup</a>
                </span>
            </span>
        </span>
    {% endfor %}
{% endpartialdef %}

<div class="atlas {% if case.scrapped %}atlas-scrapped{% endif %}">
    <h2>Case: {{ case.title }}</h2>
    {% if case.previous_case or case.next_case %}
        <div class="alert alert-info" role="alert">
            This case is part of a <a href='{% url "atlas:linked_cases_overview" case.pk %}'>series.</a><br/>
            <div class="row">
                {% if case.previous_case %}
                    <div class="col-sm-6 mb-3 mb-sm-0">
                        <h5 class="card-title">Previous Case</h5>
                        {{ case.previous_case.get_link }}
                    </div>
                {% endif %}
                {% if case.next_case %}
                    <div class="col-sm-6">
                        <h5 class="card-title">Next Case</h5>
                        {{ case.next_case.get_link }}
                    </div>
                {% endif %}
            </div>
        </div>
    {% endif %}
    <div>

        {% if case.cimar_uuid %}

            <details><summary>Details</summary>
                Case uuid: {{case.cimar_uuid}}
                <br/>

                {% if cimar_sid %}
                    <a href="{{case.get_cimar_case.viewer_link}}?sid={{cimar_sid}}" target="_blank">External</a>
                {% else %}
                    <a href="{{case.get_cimar_case.viewer_link}}" target="_blank">External</a>

                {% endif %}


                <button
                    hx-get='{% url "cimar_study_viewer_embed" case.cimar_uuid %}'
                    hx-target="#modals-here"
                    hx-trigger="click"
                    data-bs-toggle="modal"
                    data-bs-target="#modals-here"
                    class="btn primary">Open Modal</button>

                <div id="modals-here"
                     class="modal modal-blur fade"
                     style="display: none"
                     aria-hidden="false"
                     tabindex="-1">
                    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
                        <div class="modal-content"></div>
                    </div>
                </div>

                <a href='{% url "cimar_study_viewer" case.cimar_uuid %}'>Viewer</a>


                <details>
                    <summary>Study details</summary>
                    {{ case.get_cimar_case.get_pretty_study_details }}
                </details>
                <details>
                    <summary>Study schema</summary>
                    {{ case.get_cimar_case.get_pretty_study_schema }}
                </details>
                <details>
                    <summary>Study series</summary>
                    <button
                        id='load-series'
                        hx-get='{% url "cimar_study_series_block" case.cimar_uuid %}'
                        hx-trigger='load'
                        hx-swap='outerHTML'>
                        Load Series
                    </button>
                </details>
                <a href='{% url "generic:cimar_case_refresh" case.cimar_uuid %}'>Refresh</a>

            </details>



        {% else %}
                <div class="btn-group link-buttons" role="group">
                    <button type="button" class="btn btn-primary" onclick="window.location.href='/ohif/viewer/dicomjson?url=https://www.penracourses.org.uk{% url 'atlas:case_dicom_json' case.pk %}'">View case in OHIF</button>
                    <button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown" aria-expanded="false">
                        <span class="visually-hidden">Toggle dropdown</span>
                    </button>
                    <ul class="dropdown-menu">
                        <li>
                            <a class="dropdown-item" target="_blank" href="/ohif/viewer/dicomjson?url=https://www.penracourses.org.uk{% url 'atlas:case_dicom_json' case.pk %}">Open in new tab</a>
                        </li>
                    </ul>
                </div>
        {% endif %}

    <div class="clearfix mb-2">
        <div class="float-start">
            <span class="id">ID: {{ case.id }}</span>
            <span class="mx-1">/</span>
            <span class="date">{{ case.created_date|date:"d/m/Y" }}</span>
        </div>

        <div class="float-end text-end">
            {# Subspecialty badges (preserve any anchor returned by get_link) #}
            {% if case.subspecialty.all %}
                {% for sub in case.subspecialty.all %}
                    <span class="badge bg-secondary ms-1">{{ sub.get_link|safe }}</span>
                {% endfor %}
            {% else %}
                <span class="text-muted me-2">No subspecialty</span>
            {% endif %}

            {# Pathological process badges #}
            {% if case.pathological_process.all %}
                {% for p in case.pathological_process.all %}
                    <span class="badge bg-secondary ms-1">{{ p.get_link|safe }}</span>
                {% endfor %}
            {% endif %}

            {# Diagnostic certainty as a badge #}
            Diagnostic certainty: <span class="badge bg-info text-dark ms-2">{{ case.get_diagnostic_certainty_display }}</span>
            {# Normal toggle HTMX block #}
            <div class="mt-1">
                {% include "atlas/partials/_normal_toggle.html" %}
            </div>
        </div>
    </div>

        <details id="dicom-viewer-details">
            <summary>Viewer</summary>

            <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-named-stacks='{{case.get_case_named_stacks}}'
            ></div>
        </details>

        <p class="pre-whitespace"><b>Description:</b> {{ case.description }}</p>

        <p>
            <b>Presentation:</b>
            <ul>
                {% for presentation in case.presentation.all %}
                    <li>{{presentation.get_link}}</li>
                {% endfor %}
            </ul>
        </p>

    <div class="row g-3 mb-3">
            <div class="col-12 col-md-12">
                <div class="card h-100">
                    <div class="card-header">History</div>
                    <div class="card-body">
                        <div class="pre-whitespace">{{ case.history|linebreaks }}</div>
                    </div>
                </div>
            </div>
            <div class="col-12 col-md-12">
                <div class="card h-100">
                    <div class="card-header">Discussion</div>
                    <div class="card-body">
                        <div class="pre-whitespace">{{ case.discussion|linebreaks }}</div>
                    </div>
                </div>
            </div>
            <div class="col-12 col-md-12">
                <div class="card h-100">
                    <div class="card-header">Report</div>
                    <div class="card-body">
                        <div class="pre-whitespace">{{ case.report|linebreaks }}</div>
                    </div>
                </div>
            </div>
        </div>
        <p class="pre-whitespace"><b>Resource</b><br/>{% for caseresource in case.caseresource_set.all %}
            <a href='{% url "atlas:resource_detail" caseresource.resource.pk %}'>{{caseresource.resource.name}}</a>
            {% if caseresource.pre_review %}
                <span title="This resource will be avalible to review when or taking a case">(pre)</span>
            {% else %}
                <span title="This resource will only be available when reviewing a completed case">(post)</span>
            {% endif %}
        {% endfor %}
        </p>

        <div class="pre-whitespace multi-image-block"><b>Series:</b>
            <form>
                <div class="d-flex flex-wrap gap-2 align-items-start" id="case-series-row">
                    {% partial case-series %}
                </div>
            </form>
            <span>
                <button type="button"
                        class="btn btn-info"
                        onclick="window.location.href='{% url 'atlas:user_uploads_case' case_id=case.pk %}'">
                    Import new uploads
                </button><br />
                <details class="series-actions" id="series-actions">
                    <summary>
                        <button type="button" class="btn btn-primary" title="Click to manage series" onclick="this.closest('details').open = !this.closest('details').open;">
                            Manage Series
                        </button>
                    </summary>
                    <a href="{% url 'atlas:series_id_create' pk=case.pk %}">Create and add new series</a><br />
                    <button hx-get="{% url 'atlas:case_order_dicom' pk=case.pk %}"
                            title="order dicom by slice location"
                            hx-target="#series-action-results"
                            hx-swap="innerHTML"
                            hx-confirm="This will reorder all case series based upon slice location"
                    >
                        Order dicoms by slice location
                    </button>
                    <button hx-post="{% url 'atlas:combine_series' %}"
                            title="merge series"
                            hx-include="[name='series-ids']"
                            hx-target="#series-action-results"
                            hx-swap="innerHTML"
                            hx-confirm="This will merge all selected series into one"
                    >
                        Merge selected series
                    </button>
                    <button hx-post="{% url 'atlas:use_dates_as_descriptions' case.pk %}"
                            title="merge series"
                            hx-include="[name='series-ids']"
                            hx-target="#series-action-results"
                            hx-swap="innerHTML"
                            hx-confirm="This will use the dicom date as the series description"
                    >
                        Use dates as description
                    </button>
                    <button hx-post="{% url 'atlas:remove_selected_series_from_case' case.pk %}"
                            title="remove selected series from this case"
                            hx-include="[name='series-ids']:checked"
                            hx-target="#series-action-results"
                            hx-swap="innerHTML"
                            hx-confirm="Are you sure you want to remove the selected series from this case? They will not be deleted from the database."
                            class="btn btn-warning mt-2"
                            type="button"
                    >
                        Remove selected series from case
                    </button>
                    <button type="button"
                            class="btn btn-secondary mt-2"
                            data-bs-toggle="modal"
                            data-bs-target="#reorderSeriesModal">
                        Reorder series
                    </button>
                    <br/>
                    <div class="alert alert-info mt-2" id="series-action-alert" style="display:none;">
                        <span id="series-action-results" ></span>
                    </div>
                </details>

            </span>
        </div>
    {% comment %} <p><b>Scrapped:</b> {{ case.scrapped }} <a
            href="{% url 'atlas:case_scrap' pk=case.pk %}">(toggle)</a> {% endcomment %}

        <div class="atlas-answer">
            <div class="pre-whitespace">
                Condition:
                <ul>
                    {% for con in case.condition.all %}
                        <li>{{con.get_link}}</li>
                    {% endfor %}
                </ul>
                <div>
                    <details open>
                        <summary><b>Findings</b></summary>

                        {% if can_edit %}
                            <details class="help-text">
                                <summary><i class="bi bi-info-circle"></i> Help</summary>
                                <p>Findings are display sets that can be added to series. Once added they will appear here on linked cases.</p>
                                <p>To add a finding to a series, select the series and then click the "Add finding" button.</p>
                            </details>
                        {% endif %}

    <!-- Series Findings -->
                        <h5>Series Findings</h5>
                        {% if case.ordered_series %}
                            {% for series in case.ordered_series %}
                                {% for finding in series.findings.all %}
                                    <div class="finding-box" id="finding-box-{{ finding.pk }}" data-series="{{ series.pk }}">
                                        <span>
                                            <a href="{{series.get_absolute_url}}?show_finding={{finding.pk}}">
                                                <button class="btn btn-primary btn-sm">View</button>
                                            </a>
                                            <button class="btn btn-secondary btn-sm view-finding-modal" data-finding-id="{{ finding.pk }}" data-series-id="{{ series.pk }}">
                                                View in Modal
                                            </button>
                                        </span>
                                        {% if finding.findings %}
                                            <span>
                                                Findings: {% for f in finding.findings.all %}
                                                    {{f.get_link}},&nbsp;
                                                {% endfor %}
                                            </span>
                                        {% endif %}
                                        {% if finding.conditions %}
                                            <span>
                                                Conditions: {% for c in finding.conditions.all %}
                                                    {{c.get_link}},&nbsp;
                                                {% endfor %}
                                            </span>
                                        {% endif %}
                                        {% if finding.structures %}
                                            <span>
                                                Structure: {% for s in finding.structures.all %}
                                                    {{s.get_link}},&nbsp;
                                                {% endfor %}
                                            </span>
                                        {% endif %}
                                        {% if finding.description %}
                                            <span>
                                                Description: {{finding.description}}
                                            </span>
                                        {% endif %}
                                    </div>
                                {% endfor %}
                            {% endfor %}
                        {% else %}
                            No series associated with case.
                        {% endif %}

    <!-- Case Display Sets -->
                        <h5 class="mt-3">Case Display Sets</h5>
                        {% if case.display_sets %}
                            <ul class="list-group">
                                {% for ds in case.display_sets.all %}
                                    <li class="list-group-item">
                                        <b>Name: {{ ds.name }}</b>
                                        {% if ds.description %}
                                            <span class="text-muted">({{ ds.description }})</span>
                                        {% endif %}
                                        <span>
                                            <a href="{% url 'atlas:case_displaysets_detail' ds.pk %}">View Display Set</a>
                                        </span>
                                        <div>
                                            <strong>Findings:</strong>
                                            {% if ds.findings.all %}
                                                <ul>
                                                    {% for finding in ds.findings.all %}
                                                        <li>{{ finding }}</li>
                                                    {% endfor %}
                                                </ul>
                                            {% else %}
                                                <span class="text-muted">None</span>
                                            {% endif %}
                                        </div>
                                        <div>
                                            <strong>Structures:</strong>
                                            {% if ds.structures.all %}
                                                <ul>
                                                    {% for structure in ds.structures.all %}
                                                        <li>{{ structure }}</li>
                                                    {% endfor %}
                                                </ul>
                                            {% else %}
                                                <span class="text-muted">None</span>
                                            {% endif %}
                                        </div>
                                        <div>
                                            <strong>Conditions:</strong>
                                            {% if ds.conditions.all %}
                                                <ul>
                                                    {% for condition in ds.conditions.all %}
                                                        <li>{{ condition }}</li>
                                                    {% endfor %}
                                                </ul>
                                            {% else %}
                                                <span class="text-muted">None</span>
                                            {% endif %}
                                        </div>
                                        <div>
                                            <details>
                                                <summary class="small text-muted" style="cursor:pointer;">Show advanced (viewer state & annotations)</summary>
                                                <div>
                                                    <strong>Viewer State:</strong>
                                <pre class="small">{{ ds.viewerstate|default:"{}" }}</pre>
                                                </div>
                                                <div>
                                                    <strong>Annotations:</strong>
                                <pre class="small">{{ ds.annotations|default:"{}" }}</pre>
                                                </div>
                                            </details>
                                        </div>
                                    </li>
                                {% endfor %}
                            </ul>
                        {% else %}
                            <span class="text-muted">No display sets for this case.</span>
                        {% endif %}
                    </details>
                </div>
                <div>
                    <details open>
                        <summary><b>Differentials</b></summary>
                        <ul>
                            {% for diff in case.differentialcase.all %}
                                <li>{{diff.condition.get_link}} - {{diff.text}}</li>
                            {% endfor %}
                        </ul>
                    </details>
                </div>
            </div>
        </div>

        <b>Collections:</b>

        {% if can_edit %}
            <button
                hx-get="{% url 'atlas:case_collection_form' case.pk %}"
                hx-target="#collection-form">
                Add to collection</button>
        {% endif %}
        <div id="collection-form"></div>
        <ul>
            {% for collection in case.casecollection_set.all %}
                <li id="collection-{{ collection.pk }}">
                    <a href="{% url 'atlas:collection_detail' pk=collection.pk %}">{{ collection.name }}</a>
                    {% if can_edit %}
                        <button
                            class="btn btn-danger btn-sm remove-button"
                            hx-post="{% url 'atlas:remove_case_from_collection' case.pk collection.pk %}"
                            hx-target="#collection-{{ collection.pk }}"
                            hx-swap="outerHTML"
                            hx-confirm="Are you sure you want to remove this case from the collection?">
                            Remove
                        </button>
                    {% endif %}
                </li>
            {% endfor %}
        </ul>
    </p>

    
    {% if casedetail %}
        {% include 'atlas/partials/collection_question_block.html' with can_edit=can_edit %}
        
    {% endif %}
        



    <p class="pre-whitespace"><b>Previous case:</b> {{ case.previous_case.get_link }}</p>
    <p class="pre-whitespace"><b>Next case:</b>
        {% if case.next_case %}
            {{ case.next_case.get_link }}
        {% else %}
            <a href="{% url 'atlas:case_clone_next' case.pk %}">Clone and add next case</a>
        {% endif %}
    </p>
    <div>
        {% include 'question_notes.html' %}

    </div>

    <p><b>Checked by:</b> {% for verified in case.verified.all %} <a
        href="{% url 'atlas:verified_detail' pk=verified.pk %}">{{verified}}</a>, {% endfor %}</p>

    <p><b>Author(s):</b> {% for author in case.author.all %} <a
        href="{% url 'atlas:author_detail' pk=author.pk %}">{{author}}</a>, {% endfor %}</p>


    <p><b>Case size:</b> {{ case.get_total_series_images_size | filesizeformat }}</p>

    <div class="modal fade" id="findingModal" tabindex="-1" aria-labelledby="findingModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="findingModalLabel">Finding Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="findingModalBody">
                <!-- Finding details will be loaded here dynamically -->
                    <p>Loading...</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
<!-- Reorder Series Modal -->
    <div class="modal fade" id="reorderSeriesModal" tabindex="-1" aria-labelledby="reorderSeriesModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <form method="post" action="{% url 'atlas:reorder_series' case.pk %}" id="reorder-series-form">
                {% csrf_token %}
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="reorderSeriesModalLabel">Reorder Series</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <ul id="series-reorder-list" class="list-group">
                            {% for series in case.get_ordered_series %}
                                <li class="list-group-item d-flex justify-content-between align-items-center" data-series-id="{{ series.pk }}">
                                    <span>
                                        <span class="series-block-series-number">Series {{ forloop.counter }}:</span>
                                        {{ series.get_block|default:series }}
                                    </span>
                                    <span>
                                        <button type="button" class="btn btn-sm btn-outline-secondary move-up">↑</button>
                                        <button type="button" class="btn btn-sm btn-outline-secondary move-down">↓</button>
                                    </span>
                                    <input type="hidden" name="series_order" value="{{ series.pk }}">
                                </li>
                            {% endfor %}
                        </ul>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">Save order</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <script>
    // From series_viewer.html
        function loadAnnotationAndViewportOnElement(annotation, viewport, dicom_element, current_image_id_index) {
            cornerstoneTools.globalImageIdSpecificToolStateManager.clear(dicom_element);
            cornerstone.getEnabledElement(dicom_element).viewport = viewport
            cornerstoneTools.globalImageIdSpecificToolStateManager.restoreToolState(
                annotation);
            console.log("annotation", annotation)
            console.log("viewport", viewport)

        //cornerstone.getEnabledElement(dicom_element).toolStateManager.restoreToolState(annotationjson)
            cornerstone.resize(dicom_element);
            console.log("current_image_id_index", current_image_id_index)
        //current_image_id_index = parseInt(current_image_id_index);

            console.log(current_image_id_index, Number.isInteger(current_image_id_index))
            if (Number.isInteger(current_image_id_index)) {
                console.log("loading stack index")
                dicomViewer.loadStackIndex(current_image_id_index, dicom_element);
            } else {
                try {
                    console.log("current_image_id_index", current_image_id_index)
                    dicomViewer.loadImageById(current_image_id_index, dicom_element);
                } catch (e) {
                    console.log(e)
                    console.log("loading image by id failed")
                    console.log("loading next annotation image")
                    dicomViewer.getNextAnnotationImage(dicom_element);
                }
            }

        }

        document.addEventListener("DOMContentLoaded", function () {

            const dicomDetails = document.getElementById("dicom-viewer-details");
            let dicomViewerLoaded = false;
            dicomDetails.addEventListener("toggle", function() {
                if (!dicomViewerLoaded && dicomDetails.open) {
                    window.mountDicomViewers();
                    dicomViewerLoaded = true;
                }
            });


            // Move up/down logic
            document.querySelectorAll("#series-reorder-list .move-up, #series-reorder-list .move-down").forEach(function(btn) {
                btn.addEventListener("click", function(e) {
                    e.preventDefault();
                    const li = btn.closest("li");
                    if (btn.classList.contains("move-up") && li.previousElementSibling) {
                        li.parentNode.insertBefore(li, li.previousElementSibling);
                    }
                    if (btn.classList.contains("move-down") && li.nextElementSibling) {
                        li.parentNode.insertBefore(li.nextElementSibling, li);
                    }
                });
            });

    // On submit, update the hidden inputs to match the new order
            document.getElementById("reorder-series-form").addEventListener("submit", function(e) {
                const lis = document.querynelectorAll("#series-reorder-list li");
                lis.forEach((li, idx) => {
                    li.querySelector("input[name='series_order']").setAttribute("name", "series_order_" + idx);
                });
            });

// Drag and drop reordering for series list
            const reorderList = document.getElementById("series-reorder-list");
            let draggedItem = null;

            if (reorderList) {
                reorderList.querySelectorAll("li").forEach(function(li) {
                    li.setAttribute("draggable", "true");

                    li.addEventListener("dragstart", function(e) {
                        draggedItem = li;
                        li.classList.add("dragging");
                        e.dataTransfer.effectAllowed = "move";
                    });

                    li.addEventListener("dragend", function() {
                        draggedItem = null;
                        li.classList.remove("dragging");
                    });

                    li.addEventListener("dragover", function(e) {
                        e.preventDefault();
                        e.dataTransfer.dropEffect = "move";
            // Visual feedback
                        li.classList.add("drag-over");
                    });

                    li.addEventListener("dragleave", function() {
                        li.classList.remove("drag-over");
                    });

                    li.addEventListener("drop", function(e) {
                        e.preventDefault();
                        li.classList.remove("drag-over");
                        if (draggedItem && draggedItem !== li) {
                // Insert before or after depending on mouse position
                            const bounding = li.getBoundingClientRect();
                            const offset = e.clientY - bounding.top;
                            if (offset < bounding.height / 2) {
                                li.parentNode.insertBefore(draggedItem, li);
                            } else {
                                li.parentNode.insertBefore(draggedItem, li.nextSibling);
                            }
                        }
                    });
                });
            }


            const detailsElement = document.getElementById("series-actions");
            const buttons = document.querySelectorAll(".select-series-btn");

            function toggleCheckboxes() {
                const isOpen = detailsElement.hasAttribute("open");
                buttons.forEach(button => {
                    button.style.display = isOpen ? "inline-block" : "none";
                });
            }
            document.querySelectorAll(".select-series-btn").forEach(function(btn) {
                btn.addEventListener("click", function() {
                    const parent = btn.closest(".series-block");
                    const checkbox = parent.querySelector("input[type='checkbox'][name='series-ids']");
                    checkbox.checked = !checkbox.checked;
                    btn.classList.toggle("btn-primary", checkbox.checked);
                    btn.classList.toggle("btn-outline-primary", !checkbox.checked);
                    btn.textContent = checkbox.checked ? "Selected" : "Select";
                    // Highlight the series-block when selected
                    if (checkbox.checked) {
                        parent.classList.add("highlight-series");
                    } else {
                        parent.classList.remove("highlight-series");
                    }
                });
            });

        // Initial state
            toggleCheckboxes();


    // Show the alert when a result is received
            const resultsSpan = document.getElementById("series-action-results");
            const alertDiv = document.getElementById("series-action-alert");
            const observer = new MutationObserver(function(mutations) {
                if (resultsSpan.textContent.trim() !== "") {
                    alertDiv.style.display = "block";
                } else {
                    alertDiv.style.display = "none";
                }
            });
            observer.observe(resultsSpan, { childList: true, subtree: true });

        // Listen for toggle events on the <details> element
            detailsElement.addEventListener("toggle", toggleCheckboxes);

            const modal = new bootstrap.Modal(document.getElementById("findingModal"));
            const modalBody = document.getElementById("findingModalBody");

            document.querySelectorAll(".view-finding-modal").forEach(button => {
                button.addEventListener("click", function () {
                    const findingId = this.getAttribute("data-finding-id");
                    const seriesId = this.getAttribute("data-series-id");

            // Show loading text
                    modalBody.innerHTML = "<p>Loading...</p>";

            // Fetch the finding details (replace with your actual endpoint)
                    fetch(`/atlas/series_finding/${findingId}/details/`)
                        .then(response => response.text())
                        .then(html => {
                            modalBody.innerHTML = html; // Load the fetched HTML into the modal body
                            load_3d = false;
                            viewer_element_3d = document.getElementById('root');
                            if (viewer_element_3d.dataset.viewerstate3d != undefined) {
                                load_3d = true;
                                viewerState = JSON.parse(viewer_element_3d.dataset.viewerstate3d || {});
                                annotationjson3d = JSON.parse(viewer_element_3d.dataset.annotationjson3d || {});
                            } else {
                                viewer_element_3d = null;
                            }
                            // We have a slight delay to allow the viewer to load
                            setTimeout(function () {
                                // Then we load the annotation and viewport
                                window.mountDicomViewers();
                                if (load_3d) {
                                    console.log("loading 3d")

                                    //setTimeout(function () {
                                    //    console.log("loading 3d annotation")
                                    //    importAnnotations_root(annotationjson3d)
                                    //    importViewerState_root(viewerState);
                                    //}, 1000);
                                } else {
                                    console.log("not loading 3d")
                                }
                            }, 200);

                            document.getElementById("reload-finding").addEventListener("click", function () {
                                window.mountDicomViewers();
                            });

        // Initialize the DICOM viewer with the images and annotations
                        })
                        .catch(error => {
                            console.error("Error loading finding details:", error);
                            modalBody.innerHTML = "<p>Failed to load finding details.</p>";
                        });

            // Show the modal
                    modal.show();
                });
            });

        });


    </script>

    <style>
    /* Highlight style for the series-block */
        .highlight-series {
            background-color: blue;
            transition: background-color 0.3s ease, border 0.3s ease;
        }
        /* Make series blocks act as flex items and wrap neatly on small screens */
        .series-block {
            display: inline-block;
            vertical-align: top;
            min-width: 180px;
            max-width: 320px;
            margin-right: 0.5rem;
        }
        #series-reorder-list .dragging {
            opacity: 0.5;
        }
        #series-reorder-list .drag-over {
            border-top: 2px solid #0d6efd;
        }
        .series-actions[open] {
            border: 2px solid #0d6efd;
            border-radius: 6px;
            padding: 8px;
            margin-top: 8px;
        }
        .link-buttons {
            float: right;
        }
    </style>