{% load static %}
<!DOCTYPE html>
<html>
    <head>
        <title>Viewer</title>
        <style type="text/css">
            body, html {
                margin: 0; padding: 0; height: 100%; overflow: hidden;
            }
            #viewer {
                position:absolute; left: 0; right: 0; bottom: 0; top: 0px;
            }
            /* Modal styles */
            .center-modal {
                position: fixed;
                top: 0; left: 0; right: 0; bottom: 0;
                width: 100vw; height: 100vh;
                background: rgba(20,20,30,0.96);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 1000;
            }
            .center-modal-content {
                background: #23232b;
                color: #eee;
                padding: 2em 2.5em;
                border-radius: 12px;
                box-shadow: 0 4px 32px rgba(0,0,0,0.4);
                max-width: 90vw;
                max-height: 80vh;
                text-align: center;
                font-size: 1.2em;
            }
            .highlight-action {
                display: inline-block;
                background: #0d6efd;
                color: #fff;
                font-weight: bold;
                padding: 0.4em 1em;
                border-radius: 6px;
                margin: 0.7em 0 1.2em 0;
                font-size: 1.3em;
                box-shadow: 0 2px 8px rgba(13,110,253,0.15);
                letter-spacing: 0.03em;
            }
            .center-modal-content ul {
                color: #bdbdbd;
            }
            .center-modal-content h2 {
                color: #fff;
            }
        </style>
        <script src="{% static 'dv3d/index.js' %}" type="module" defer="defer"></script>
    </head>

    <body>
        <!-- Centered modal for instructions -->
        <div id="awaiting-modal" class="center-modal">
            <div class="center-modal-content">
                <span class="highlight-action">Share this screen</span>
                <h2>Awaiting Load Request</h2>
                <p>This page will display a DICOM series when loaded from another page.</p>
                <ul style="text-align:left; margin: 1em auto; max-width: 30em;">
                    <li>Return to the previous page and select a series to view.</li>
                    <li>This viewer will update automatically when a series is loaded.</li>
                    <li>Keep this tab open to receive data.</li>
                </ul>
            </div>
        </div>
        <div id="root" class="dicom-viewer-root"
             style="box-sizing: border-box; background: #222; position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 100vw; height: 100vh;"
             data-auto-cache-stack="true"
        ></div>

        <!-- Overlay for non-DICOM resources (images/videos/embeds) -->
        <div id="resourceDisplay" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.96); z-index:100000; align-items:center; justify-content:center;">
            <div id="resourceInner" style="max-width:95vw; max-height:95vh; display:flex; align-items:center; justify-content:center;"></div>
            <button id="resourceClose" style="position:fixed; top:12px; right:12px; z-index:2001;" class="btn btn-sm btn-light">Close</button>
        </div>

        <script type="text/javascript">
            var win2 = false;

            document.addEventListener("DOMContentLoaded", function() {
                document.title = "Case: {{current_case.title}}";
                console.log('ready');
                const bc = new BroadcastChannel("viva_load");
                const POPOUT_STATE_KEY = 'rad_local_viewer_popout_state';

                // Centralized hide helper and delegated close handling for local viewer
                function hideResourceLocal(){ const disp=document.getElementById('resourceDisplay'); const inner=document.getElementById('resourceInner'); if(disp) disp.style.display='none'; if(inner) inner.innerHTML=''; }
                (function(){ const disp=document.getElementById('resourceDisplay'); if(!disp) return; disp.addEventListener('click', function(e){ const close = e.target.closest && e.target.closest('#resourceClose'); if (close) hideResourceLocal(); }); })();

                // Helper to safely mount the DICOM viewers (waits for bundle and layout)
                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); }
                }

                function applyViewerPayload(payload) {
                    if (!payload || payload.type !== 'open') {
                        return;
                    }

                    var root = document.getElementById('root');
                    var awaiting = document.getElementById('awaiting-modal');
                    if (!root) {
                        return;
                    }

                    if (awaiting) {
                        awaiting.style.display = 'none';
                    }

                    if (payload.namedStacks) {
                        root.dataset.namedStacks = payload.namedStacks;
                    } else {
                        delete root.dataset.namedStacks;
                    }

                    if (payload.images) {
                        root.dataset.images = payload.images;
                    } else {
                        delete root.dataset.images;
                    }

                    if (payload.viewerstate && Object.keys(payload.viewerstate).length > 0) {
                        root.dataset.viewerstate = payload.viewerstate;
                    } else {
                        delete root.dataset.viewerstate;
                    }

                    if (payload.annotations && Object.keys(payload.annotations).length > 0) {
                        root.dataset.annotationjson = payload.annotations;
                    } else {
                        delete root.dataset.annotationjson;
                    }

                    mountDicomViewersSafely();
                }

                function persistViewerPayload(payload) {
                    try {
                        localStorage.setItem(POPOUT_STATE_KEY, JSON.stringify(payload));
                    } catch (e) {
                        console.warn('Could not persist viewer payload', e);
                    }
                }

                function readPersistedViewerPayload() {
                    try {
                        var saved = localStorage.getItem(POPOUT_STATE_KEY);
                        return saved ? JSON.parse(saved) : null;
                    } catch (e) {
                        console.warn('Could not read persisted viewer payload', e);
                        return null;
                    }
                }

                var savedPayload = readPersistedViewerPayload();
                if (savedPayload) {
                    applyViewerPayload(savedPayload);
                }

                window.addEventListener('storage', function (event) {
                    if (event.key !== POPOUT_STATE_KEY || !event.newValue) {
                        return;
                    }

                    try {
                        applyViewerPayload(JSON.parse(event.newValue));
                    } catch (e) {
                        console.warn('Could not parse updated viewer payload', e);
                    }
                });

                bc.onmessage = (event) => {
                    // Ensure any existing overlay is closed on new load
                    try { hideResourceLocal(); } catch(_) {}
                    console.log("message received");
                    console.log(event);
                    if (event.data.type == "open") {
                        // If a resource URL is provided (image/video/embed), show it in overlay
                        function isMediaUrl(url) {
                            if (!url) return false;
                            const lower = url.toLowerCase();
                            if (lower.match(/\.(jpe?g|png|gif|webp|svg)(?:$|\?|#)/)) return 'image';
                            if (lower.match(/\.(mp4|webm|ogg)(?:$|\?|#)/)) return 'video';
                            if (lower.indexOf('youtube.com') !== -1 || lower.indexOf('youtu.be') !== -1) return 'embed';
                            if (lower.indexOf('vimeo.com') !== -1) return 'embed';
                            return false;
                        }

                        function showResource(url) {
                            const type = isMediaUrl(url);
                            const disp = document.getElementById('resourceDisplay');
                            const inner = document.getElementById('resourceInner');
                            inner.innerHTML = '';
                            if (!type) return false;

                            const transformWrap = document.createElement('div');
                            transformWrap.style.display = 'flex'; transformWrap.style.alignItems = 'center'; transformWrap.style.justifyContent = 'center';
                            transformWrap.style.width = '100%'; transformWrap.style.height = '100%'; transformWrap.style.overflow = 'hidden'; transformWrap.style.touchAction = 'none';

                            if (type === 'image') {
                                const img = document.createElement('img'); img.src = url; img.style.maxWidth = '95%'; img.style.maxHeight = '95%'; img.style.objectFit = 'contain'; img.style.cursor='grab'; img.draggable=false; transformWrap.appendChild(img);
                            } else if (type === 'video') {
                                const v = document.createElement('video'); v.controls=true; v.autoplay=false; v.style.maxWidth='95%'; v.style.maxHeight='95%'; v.style.objectFit='contain'; const s=document.createElement('source'); s.src=url; v.appendChild(s); transformWrap.appendChild(v);
                            } else if (type === 'embed') {
                                let embed = url; try{ const m=url.match(/(?:v=|v\/|embed\/|youtu\.be\/)([A-Za-z0-9_-]{6,})/); if (m&&m[1]) embed='https://www.youtube.com/embed/'+m[1]; else if (url.indexOf('vimeo.com')!==-1){ const m2=url.match(/vimeo\.com\/(\d+)/); if(m2&&m2[1]) embed='https://player.vimeo.com/video/'+m2[1]; } }catch(e){}
                                const iframe=document.createElement('iframe'); iframe.src=embed; iframe.setAttribute('frameborder','0'); iframe.setAttribute('allowfullscreen',''); iframe.style.width='95%'; iframe.style.height='85%'; transformWrap.appendChild(iframe);
                            }

                            inner.appendChild(transformWrap);

                            // pan/zoom
                            (function enablePanZoom(target){
                                let scale=1, minScale=0.5, maxScale=6, startX=0, startY=0, translateX=0, translateY=0, dragging=false;
                                const content=target.firstElementChild;
                                function update(){ if(content) content.style.transform=`translate(${translateX}px, ${translateY}px) scale(${scale})`; }
                                target.addEventListener('wheel', function(e){
                                    const dispEl = document.getElementById('resourceDisplay');
                                    if (!dispEl || dispEl.style.display === 'none') return;
                                    e.preventDefault();
                                    const delta=-e.deltaY||e.wheelDelta; const zoom=delta>0?1.12:0.9; const newScale=Math.min(maxScale, Math.max(minScale, scale*zoom)); const rect=content.getBoundingClientRect(); const mx=e.clientX-rect.left, my=e.clientY-rect.top; const ratio=newScale/scale-1; translateX -= (mx-rect.width/2)*ratio; translateY -= (my-rect.height/2)*ratio; scale=newScale; update();
                                }, {passive:false});
                                target.addEventListener('pointerdown', function(e){ dragging=true; startX=e.clientX; startY=e.clientY; target.setPointerCapture(e.pointerId); if(content) content.style.cursor='grabbing'; });
                                target.addEventListener('pointermove', function(e){ if(!dragging) return; e.preventDefault(); const dx=e.clientX-startX, dy=e.clientY-startY; startX=e.clientX; startY=e.clientY; translateX+=dx; translateY+=dy; update(); });
                                target.addEventListener('pointerup', function(e){ dragging=false; try{target.releasePointerCapture(e.pointerId)}catch(_){} if(content) content.style.cursor='grab'; });
                                target.addEventListener('dblclick', function(){ scale=1; translateX=0; translateY=0; update(); });
                                document.addEventListener('keydown', function(ev){ if(ev.key==='Escape'){ document.getElementById('resourceDisplay').style.display='none'; document.getElementById('resourceInner').innerHTML=''; } });
                            })(transformWrap);

                        disp.style.display='flex'; return true;
                    }



                    if (event.data.url && isMediaUrl(event.data.url)) {
                            // show resource overlay and do not attempt to mount DICOM viewer
                        if (showResource(event.data.url)) {
                            persistViewerPayload(event.data);
                            bc.postMessage({"type": "open-complete-local"});
                            return;
                        }
                    }
                    persistViewerPayload(event.data);
                    applyViewerPayload(event.data);
                    bc.postMessage({"type": "open-complete-local"});
                }
            };
            });
        </script>

    </body>
</html>