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

{% block content %}
    <div class="container py-3 viva-local-page">
        <div class="card border-secondary-subtle shadow-sm mb-3">
            <div class="card-body d-flex flex-wrap gap-2 justify-content-between align-items-center">
                <div>
                    <h1 class="h4 mb-1">Viva Cases (Local Viewer)</h1>
                    <p class="text-muted mb-0">Load full cases, single series, resources, or display sets into a linked local DV3D window.</p>
                </div>
                <div class="d-flex flex-wrap gap-2">
                    <button id="open-viewer-local" class="btn btn-primary">Open Viewer Local</button>
                    <button id="view-series" class="btn btn-outline-secondary">Toggle series</button>
                    <button id="toggle-edit-mode" class="btn btn-outline-warning">Enable Edit Mode</button>
                </div>
            </div>
        </div>

        <details class="help-text card border-secondary-subtle shadow-sm mb-3">
            <summary class="card-header bg-body-secondary d-flex align-items-center gap-2"><i class="bi bi-info-circle"></i> Quick help</summary>
            <div class="card-body">
                <p class="mb-2">Open the linked viewer first, then use the Load controls on this page. Loading a new case/series replaces the current viewer content.</p>
                <p class="mb-0">Use Edit Mode to reveal direct links for case, series, and display-set editing without leaving the viva workflow.</p>
            </div>
        </details>

        <div class="row g-3">
            <div class="col-lg-7">
                <h2 class="h5 mb-2">Cases</h2>
                <ol class="sortable list-unstyled d-flex flex-column gap-3">
                    {% for casedetail in casedetails %}
                        {% with case=casedetail.case %}
                            <li data-question_pk="{{ case.pk }}">
                                <article class="card border-secondary-subtle shadow-sm case-item"
                                         data-title="{{ case.title }}"
                                         data-case="{{ case.pk }}"
                                         data-casejson="{{ case.viva_details_json|urlencode }}"
                                         data-images="{{ case.series_images_nested_json|urlencode }}"
                                         data-viewerstate="{{ casedetail.default_viewerstate_string|urlencode }}">
                                    <header class="card-header d-flex flex-wrap justify-content-between align-items-center gap-2">
                                        <div>
                                            <span class="badge bg-primary me-2">Case {{ forloop.counter }}</span>
                                            <span class="fw-semibold">{{ case.title }}</span>
                                        </div>
                                        <div class="d-flex flex-wrap gap-2 align-items-center">
                                            <button class="open-case-local btn btn-sm btn-success" data-target="{{ case.pk }}" data-type="case">Load Case</button>
                                            <button class="view-link-case btn btn-outline-primary btn-sm" style="display:none;">
                                                <a href="{% url 'atlas:case_detail' case.pk %}" style="color: inherit; text-decoration: none;">View Case</a>
                                            </button>
                                            <button class="edit-link-case btn btn-outline-warning btn-sm" style="display:none;">
                                                <a href="{% url 'atlas:case_update' case.pk %}?next={{ request.get_full_path|urlencode }}" style="color: inherit; text-decoration: none;">Edit Case</a>
                                            </button>
                                        </div>
                                    </header>
                                    <div class="card-body d-flex flex-column gap-3">
                                        <details class="series-detail">
                                            <summary class="fw-semibold">Series</summary>
                                            <div class="mt-2 d-flex flex-column gap-2">
                                                {% for series in case.visible_prefetched_series %}
                                                    <div class="border rounded p-2 bg-body-tertiary">
                                                        <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
                                                            <div class="small">
                                                                <div class="fw-semibold">Series {{ forloop.counter }}</div>
                                                                <div class="text-muted">
                                                                    {% if series.modality %}{{ series.modality }}{% endif %}
                                                                    {% if series.examination %} · {{ series.examination }}{% endif %}
                                                                    {% if series.plane %} · {{ series.plane }}{% endif %}
                                                                </div>
                                                            </div>
                                                            <div class="d-flex flex-wrap gap-2 align-items-center">
                                                                <button class="open-series-local btn btn-sm btn-outline-success"
                                                                        data-type="series"
                                                                        data-series="{{ forloop.counter }}"
                                                                        data-case="{{ case.pk }}"
                                                                        data-target="{{ series.pk }}">
                                                                    Load Series
                                                                </button>
                                                                <button class="edit-link-series btn btn-outline-warning btn-sm" style="display:none;">
                                                                    <a href="{% url 'atlas:series_update' series.pk %}" style="color: inherit; text-decoration: none;">Edit Series</a>
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                {% empty %}
                                                    <div class="text-muted small">No series linked.</div>
                                                {% endfor %}
                                            </div>
                                        </details>

                                        {% if case.prefetched_case_resources %}
                                            <div>
                                                <div class="fw-semibold mb-1">Resources</div>
                                                <div class="d-flex flex-column gap-1">
                                                    {% for cr in case.prefetched_case_resources %}
                                                        {% with res=cr.resource %}
                                                            <div class="d-flex flex-wrap align-items-center gap-2 small">
                                                                <span>{{ res.name }}</span>
                                                                <button class="open-resource btn btn-sm btn-outline-primary" data-src="{% if res.file %}{{ res.file.url }}{% else %}{{ res.url }}{% endif %}" data-title="{{ res.name|escapejs }}">Load</button>
                                                            </div>
                                                        {% endwith %}
                                                    {% endfor %}
                                                </div>
                                            </div>
                                        {% endif %}

                                        {% if case.prefetched_display_sets %}
                                            <details class="displayset-detail">
                                                <summary class="fw-semibold">Display Sets</summary>
                                                <div class="mt-2 d-flex flex-column gap-2">
                                                    {% for ds in case.prefetched_display_sets %}
                                                        <div class="border rounded p-2 bg-body-tertiary d-flex flex-wrap justify-content-between align-items-center gap-2">
                                                            <div class="small">
                                                                <div class="fw-semibold">{{ ds.name }}</div>
                                                                {% if ds.description %}<div class="text-muted">{{ ds.description }}</div>{% endif %}
                                                            </div>
                                                            <div class="d-flex flex-wrap gap-2 align-items-center">
                                                                <button class="open-displayset btn btn-sm btn-outline-info"
                                                                        data-type="displayset"
                                                                        data-displayset="{{ ds.pk }}"
                                                                        data-case="{{ case.pk }}"
                                                                        data-title="{{ ds.name }}"
                                                                        data-casejson="{{ case.viva_details_json|urlencode }}"
                                                                        data-images="{{ case.series_images_nested_json|urlencode }}"
                                                                        data-viewerstate="{{ ds.viewerstate_string|urlencode }}"
                                                                        data-annotations="{{ ds.annotations_string|urlencode }}">
                                                                    Load Display Set
                                                                </button>
                                                                <button class="edit-link-displayset btn btn-outline-warning btn-sm" style="display:none;">
                                                                    <a href="{% url 'atlas:case_displaysets' case.pk %}?displayset={{ ds.pk }}&edit=true" style="color: inherit; text-decoration: none;">Edit Display Set</a>
                                                                </button>
                                                            </div>
                                                        </div>
                                                    {% endfor %}
                                                </div>
                                            </details>
                                        {% endif %}

                                        <div class="question-block-snippet" style="display:none;">
                                            {% include 'atlas/partials/collection_question_block.html' with casedetail=casedetail %}
                                        </div>
                                    </div>
                                </article>
                            </li>
                        {% endwith %}
                    {% endfor %}
                </ol>
            </div>

            <div class="col-lg-5">
                <div class="sticky-top pt-2">
                    <div class="card border-secondary-subtle shadow-sm">
                        <div class="card-header"><h2 class="h5 mb-0">Current Case</h2></div>
                        <div class="card-body" id="case-details">
                            <div id="user-message" class="alert py-2" style="display:none;"></div>
                            <div id="loading-case" class="alert alert-warning py-2" style="display:none;">Waiting for case to load in linked window.</div>
                            <div id="current-case-title" class="mb-2">None</div>
                            <div id="current-case-series" class="mb-2"></div>
                            <div id="current-case-history" class="mb-2"></div>
                            <div id="current-case-discussion" class="mb-2"></div>
                            <div id="current-case-report" class="mb-2"></div>
                            <div id="current-case-questions" class="mt-3"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}


{% block js %}
    <script type="text/javascript">
        var win2 = false;
        let editMode = false;
        let viewerConnected = false;

        $(document).ready(function() {
            const showUserMessage = function(message, level = 'warning') {
                const $msg = $('#user-message');
                $msg
                    .removeClass('alert-warning alert-danger alert-success alert-info')
                    .addClass('alert-' + level)
                    .text(message)
                    .show();
            };

            const clearUserMessage = function() {
                $('#user-message').hide().text('');
            };

            const parseEncodedJson = function(raw, label) {
                if (!raw) {
                    return {};
                }
                try {
                    return JSON.parse(decodeURIComponent(raw));
                } catch (err) {
                    throw new Error('Unable to parse ' + label + ' payload.');
                }
            };

            const ensureViewerWindowReady = function() {
                if (!win2 || win2.closed) {
                    showUserMessage('Viewer is not open. Click "Open Viewer Local" before loading a case or series.', 'warning');
                    return false;
                }
                clearUserMessage();
                return true;
            };

            // Edit mode toggle
            $('#toggle-edit-mode').click(function() {
                editMode = !editMode;
                if (editMode) {
                    $('.edit-link-case').show();
                    $('.view-link-case').show();
                    $('.edit-link-series').show();
                    $('.edit-link-displayset').show();
                    $(this).text('Disable Edit Mode').removeClass('btn-warning').addClass('btn-danger');
                } else {
                    $('.edit-link-case').hide();
                    $('.view-link-case').hide();
                    $('.edit-link-series').hide();
                    $('.edit-link-displayset').hide();
                    $(this).text('Enable Edit Mode').removeClass('btn-danger').addClass('btn-warning');
                }
            });

            const bc = new BroadcastChannel("viva_load");
            bc.onmessage = (event) => {
                console.log("message received");
                console.log(event);
                if (event.data.type == "open-complete-local") {
                    viewerConnected = true;
                    $("#loading-case").hide();
                    $("#open-viewer-local").removeClass("flash-button");
                    clearUserMessage();
                    //bc.postMessage({"type": "open-complete-local"});
                }
            };
            console.log('ready')
            $('.show-collection, .show-case, .show-series').click(function() {
                var url = $(this).data('target');
                console.log('clicked', url)
                $('#case-title').text($(this).data('title'));
                $('#viewer').attr('src', url)
            });
            $('.open-case-local').click(function() {
                try {
                    if (!ensureViewerWindowReady()) {
                        return;
                    }
                    let c = this.closest(".case-item");
                    console.log('clicked local', c)
                    console.log('open local', c.dataset.case)
                    casedetails = parseEncodedJson(c.dataset.casejson, 'case details');
                    let viewerstate = parseEncodedJson(c.dataset.viewerstate, 'viewer state') || {};
                    let images = decodeURIComponent(c.dataset.images || '[]');
                    $('#loading-case').show()
                    $("#open-viewer-local").addClass("flash-button");
                    $('#current-case-title').html("<span class='title'>Case:</span> "+c.dataset.title);
                    $("#current-case-history").html("<span class='title'>History:</span> "+(casedetails['history'] || ''));
                    $("#current-case-discussion").html("<span class='title'>Discussion:</span> "+(casedetails['discussion'] || ''));
                    $("#current-case-report").html("<span class='title'>Report:</span> "+(casedetails['report'] || ''));

                    bc.postMessage({"type": "open",
                        "case" : c.dataset.case, "images": images,
                        "viewerstate": viewerstate
                    });

                    // Inject the per-case question snippet into the current case panel
                    var snippet = $(c).find('.question-block-snippet').html();
                    $('#current-case-questions').html(snippet || '');
                } catch (e) {
                    console.error('Case load failed', e);
                    showUserMessage('Case load failed: ' + (e.message || 'Unexpected error while parsing case data.'), 'danger');
                }

            });
            $('.open-displayset').click(function() {
                try {
                    if (!ensureViewerWindowReady()) {
                        return;
                    }
                    let c = this;
                    console.log('clicked local', c)
                    console.log('open local', c.dataset.case)
                    casedetails = parseEncodedJson(c.dataset.casejson, 'display set case details');
                    let viewerstate = parseEncodedJson(c.dataset.viewerstate, 'display set viewer state') || {};
                    let annotations = parseEncodedJson(c.dataset.annotations, 'display set annotations') || {};
                    let images = decodeURIComponent(c.dataset.images || '[]');
                    $('#loading-case').show()
                    $("#open-viewer-local").addClass("flash-button");
                    $('#current-case-title').html("<span class='title'>Case:</span> "+c.dataset.title);
                    $("#current-case-history").html("<span class='title'>History:</span> "+(casedetails['history'] || ''));
                    $("#current-case-discussion").html("<span class='title'>Discussion:</span> "+(casedetails['discussion'] || ''));
                    $("#current-case-report").html("<span class='title'>Report:</span> "+(casedetails['report'] || ''));

                    bc.postMessage({"type": "open",
                        "case" : c.dataset.case, "images": images,
                        "viewerstate": viewerstate,
                        "annotations": annotations
                    });

                    // Inject the per-case question snippet
                    var caseItem = $(this).closest('.case-item');
                    var snippet = caseItem.find('.question-block-snippet').html();
                    $('#current-case-questions').html(snippet || '');
                } catch (e) {
                    console.error('Display set load failed', e);
                    showUserMessage('Display set load failed: ' + (e.message || 'Unexpected error while parsing display set data.'), 'danger');
                }

            });
            $('.open-series-local').click(function() {
                try {
                    if (!ensureViewerWindowReady()) {
                        return;
                    }
                    let c = $(this).closest(".case-item")[0];
                    let seriesNumber = $(this).data('series');
                    let seriesPk = $(this).data('target');
                    let caseDetails = parseEncodedJson(c.dataset.casejson, 'series case details');
                    let allSeriesImages = parseEncodedJson(c.dataset.images, 'series images');
                    let images = allSeriesImages[seriesNumber - 1] || [];
                    $('#loading-case').show();
                    $("#open-viewer-local").addClass("flash-button");
                    $('#current-case-title').html("<span class='title'>Case:</span> " + c.dataset.title);
                    $('#current-case-series').html("<span class='title'>Series:</span> " + seriesNumber);
                    $("#current-case-history").html("<span class='title'>History:</span> " + (caseDetails['history'] || ''));
                    $("#current-case-discussion").html("<span class='title'>Discussion:</span> " + (caseDetails['discussion'] || ''));
                    $("#current-case-report").html("<span class='title'>Report:</span> " + (caseDetails['report'] || ''));

        // Send only the images for this series
                    bc.postMessage({
                        "type": "open",
                        "case": c.dataset.case,
                        "series": seriesPk,
                        "images": JSON.stringify(images),
                    });

                    // Inject the per-case question snippet
                    var snippet = $(c).find('.question-block-snippet').html();
                    $('#current-case-questions').html(snippet || '');
                } catch (e) {
                    console.error('Series load failed', e);
                    showUserMessage('Series load failed: ' + (e.message || 'Unexpected error while parsing series data.'), 'danger');
                }
            });
            // Load resource into linked viewer
            $('.open-resource').click(function() {
                try {
                    if (!ensureViewerWindowReady()) {
                        return;
                    }
                    var src = $(this).data('src');
                    var title = $(this).data('title') || 'Resource';
                    $('#loading-case').show();
                    $("#open-viewer-local").addClass("flash-button");
                    $('#current-case-title').html("<span class='title'>Resource:</span> "+title);
                    $('#current-case-history').html('');
                    $('#current-case-discussion').html('');
                    $('#current-case-report').html('');

                    bc.postMessage({"type": "open", "url": src});
                } catch (e) {
                    console.error('Resource load failed', e);
                    showUserMessage('Resource load failed: ' + (e.message || 'Unexpected error.'), 'danger');
                }
            });
            $('.send-message').click(function() {
                var url = $(this).data('target');
                bc.postMessage(url);
            })
            $('#open-viewer-local').click(function() {
                $("#open-viewer-local").removeClass("flash-button");
                viewerConnected = false;
                try {
                    localStorage.removeItem('rad_local_viewer_popout_state');
                } catch (e) {
                    console.warn('Unable to clear previous viewer state', e);
                }
                const opened = openSecondaryWindow("{% url 'atlas:collection_viewer_local_progressive' %}");
                if (!opened) {
                    showUserMessage('Unable to open viewer window. Please allow pop-ups for this site and try again.', 'danger');
                    return;
                }
                showUserMessage('Viewer window opened. Load a case to begin. If nothing appears, check pop-up blockers and re-open the viewer.', 'info');
                //bc.postMessage(url);
            })
            $('#view-series').click(function() {
                $(".series-detail").attr("open", (_, attr) => !attr);
                //document.getElementsByClassName("series-detail").toggleAttribute("open");
                //bc.postMessage(url);
            })

        });
        function openSecondaryWindow(url) {
   //return win2 = window.open(url,'secondary','width=300,height=100');
            win2 = window.open(
                url,
                'secondary',
                'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=1200,height=800'
            );
            return win2;
        }

    </script>

    {{ form.media }}
{% endblock %}

{% block css %}

    <style type="text/css">
        #loading-case {
            display: none;
            color: red;
        }
        @keyframes glowing {
            0% {
                box-shadow: 0 0 20px #a600ff;
            }
            50% {
                box-shadow: 0 0 40px #52057b;
            }
            100% {
                box-shadow: 0 0 20px #a600ff;
            }
        }
        .flash-button {
            animation: glowing 1300ms infinite;
        }

        #case-details {
            padding-bottom: 20px;
        }

        .title {
            font-weight: bold;
        }

        .edit-link-case, .edit-link-series, .edit-link-displayset {
            vertical-align: middle;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/@json-editor/json-editor@latest/dist/jsoneditor.min.js"></script>
    <script src="/static/django_jsonforms/jsoneditor_init.js"></script>
{% endblock css %}