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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
/**
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

document.addEventListener('DOMContentLoaded', () => {
    const infoDiv = document.querySelector('.info');
    const mainDiv = document.querySelector('.main');
    const reportSectionDiv = document.querySelector('.report-section');
    const viewDemoButton = document.getElementById('view-demo-button');
    const backToInfoButton = document.getElementById('back-to-info-button');
    const caseSelectorTabsContainer = document.getElementById('case-selector-tabs-container');
    const reportTextDisplay = document.getElementById('report-text-display');
    const explanationOutput = document.getElementById('explanation-output');
    const explanationContent = document.getElementById('explanation-content');
    const explanationError = document.getElementById('explanation-error');
    const imageContainer = document.getElementById('image-container');
    const reportImage = document.getElementById('report-image');
    const imageLoading = document.getElementById('image-loading');
    const imageError = document.getElementById('image-error');
    const imageModalityHeader = document.getElementById('image-modality-header'); // Get reference to the header
    const ctImageNote = document.getElementById('ct-image-note');
    const appLoading = document.getElementById('app-loading');
    const appError = document.getElementById('app-error');

    let availableReports = [];
    let currentReportName = null;
    let currentReportDetails = null;

    let explainAbortController = null;
    let reportLoadAbortController = null;
    let appLoadingTimeout = null;
    let explanationLoadingTimer = null;

    function initialize() {
        try {
            const reportsDataElement = document.getElementById('reports-data');
            if (reportsDataElement) {
                availableReports = JSON.parse(reportsDataElement.textContent);
            } else {
                displayAppError("Failed to load report list.");
                return;
            }
        } catch (e) {
            displayAppError("Failed to parse report list.");
            return;
        }

        if (availableReports.length === 0) {
            displayAppError("No reports available.");
            return;
        }

        if (viewDemoButton && infoDiv && mainDiv) {
            viewDemoButton.addEventListener('click', () => {
                infoDiv.style.display = 'none';
                mainDiv.style.display = 'grid';
                if (currentReportName) {
                    loadReportDetails(currentReportName);
                }
            });
        }

        if (backToInfoButton && infoDiv && mainDiv) {
            backToInfoButton.addEventListener('click', () => {
                abortOngoingRequests();
                mainDiv.style.display = 'none';
                infoDiv.style.display = 'flex';
                clearAllOutputs();
                currentReportDetails = null;
                reportImage.src = '';
                document.title = "Radiology Report Explainer";
            });
        }

        if (caseSelectorTabsContainer) {
            caseSelectorTabsContainer.addEventListener('click', handleCaseSelectionClick);
        }

        reportTextDisplay.addEventListener('click', handleSentenceClick);

        const firstCaseButton = caseSelectorTabsContainer?.querySelector('.nav-button-case');
        if (firstCaseButton) {
            currentReportName = firstCaseButton.dataset.reportName;
            setActiveCaseButton(firstCaseButton);
            loadReportDetails(currentReportName);
        } else {
            displayAppError("No cases found to load initially.");
        }
    }

    function handleCaseSelectionClick(event) {
        const clickedButton = event.target.closest('.nav-button-case');
        if (!clickedButton) return;

        const selectedName = clickedButton.dataset.reportName;
        if (selectedName && selectedName !== currentReportName) {
            abortOngoingRequests();
            currentReportName = selectedName;
            setActiveCaseButton(clickedButton);
            loadReportDetails(currentReportName);
        }
    }

    async function handleSentenceClick(event) {
        const clickedElement = event.target;
        if (!clickedElement.classList.contains('report-sentence') || clickedElement.tagName !== 'SPAN') return;

        const sentenceText = clickedElement.dataset.sentence;
        if (!sentenceText || !currentReportName) return;

        abortOngoingRequests(['report']);
        explainAbortController = new AbortController();
        
        document.querySelectorAll('#report-text-display .selected-sentence').forEach(el => el.classList.remove('selected-sentence'));
        clickedElement.classList.add('selected-sentence');

        adjustExplanationPosition(clickedElement);

        try {
            await Promise.all([
                fetchExplanation(sentenceText, explainAbortController.signal),
            ]);
        } catch (error) {
            if (error.name !== 'AbortError') {
                console.error("Error during sentence processing:", error);
            }
        }
    }

    async function loadReportDetails(reportName) {
        abortOngoingRequests();
        reportLoadAbortController = new AbortController();
        const signal = reportLoadAbortController.signal;

        setLoadingState(true, 'report');
        clearAllOutputs(true);

        try {
            const response = await fetch(`/get_report_details/${encodeURIComponent(reportName)}`, { signal });
            if (signal.aborted) return;

            if (!response.ok) {
                const errorData = await response.json().catch(() => ({ error: `HTTP error ${response.status}` }));
                throw new Error(errorData.error || `HTTP error ${response.status}`);
            }

            currentReportDetails = await response.json();
            if (signal.aborted) return;

            document.title = `${reportName} - Radiology Explainer`;

            // Update the image modality header
            if (imageModalityHeader && currentReportDetails.image_type) {
                imageModalityHeader.textContent = currentReportDetails.image_type;
            }

            // Show/hide CT note based on image_type and image_file presence
            if (ctImageNote) {
                if (currentReportDetails.image_type === 'CT' && currentReportDetails.image_file) {
                    ctImageNote.style.display = 'block';
                } else {
                    ctImageNote.style.display = 'none';
                }
            }


            if (currentReportDetails.image_file) {
                const imageUrl = `${currentReportDetails.image_file}`;

                reportImage.onload = null;
                reportImage.onerror = null;

                reportImage.onload = () => {
                    imageLoading.style.display = 'none';
                    reportImage.style.display = 'block';
                    imageError.style.display = 'none';
                };
                reportImage.onerror = () => {
                    imageLoading.style.display = 'none';
                    reportImage.style.display = 'none';
                    displayImageError("Failed to load image file.");
                };

                reportImage.src = imageUrl;
                reportImage.alt = `Radiology Image for ${reportName}`;
            } else {
                displayImageError("Image path not configured for this report.");
                if (ctImageNote) ctImageNote.style.display = 'none'; // Ensure note is hidden if no image path
            }

            renderReportTextWithLineBreaks(currentReportDetails.text || '');
        } catch (error) {
            if (error.name !== 'AbortError') {
                displayReportTextError(`Failed to load report: ${error.message}`);
                // Clean up UI elements on report load error.
                if (reportImage) {
                    reportImage.style.display = 'none';
                    reportImage.src = '';
                    reportImage.onload = null;
                    reportImage.onerror = null;
                }
                if (imageLoading) imageLoading.style.display = 'none';
                if (imageError) imageError.style.display = 'none';
                if (ctImageNote) ctImageNote.style.display = 'none';
                clearExplanationAndLocationUI();
            }
        } finally {
            if (reportLoadAbortController?.signal === signal) {
                reportLoadAbortController = null;
            }
            if (!signal.aborted) {
                setLoadingState(false, 'report');
            }
        }
    }

    function renderReportTextWithLineBreaks(text) {
        reportTextDisplay.innerHTML = '';
        reportTextDisplay.classList.remove('loading', 'error');

        const lines = text.split('\n');
        if (lines.length === 0 || (lines.length === 1 && !lines[0].trim())) {
            reportTextDisplay.textContent = 'Report text is empty or could not be processed.';
            return;
        }

        lines.forEach((line, index) => {
            const trimmedLine = line.trim();
            if (trimmedLine !== '') {
                const sentences = splitSentences(trimmedLine);
                sentences.forEach(sentence => {
                    if (sentence) {
                        const span = document.createElement('span');
                        span.textContent = sentence + ' ';
                        if (!sentence.includes('Image source: ') && sentence.includes(' ') || !sentence.includes(':')) {
                            span.classList.add('report-sentence');
                        }
                        span.dataset.sentence = sentence;
                        reportTextDisplay.appendChild(span);
                    }
                });
            }
            if (index < lines.length - 1) {
                reportTextDisplay.appendChild(document.createElement('br'));
            }
        });
    }

    async function fetchExplanation(sentence, signal) {
        explanationError.style.display = 'none';
        if (!currentReportName) {
            displayExplanationError("No report selected.");
            return;
        }

    if (explanationLoadingTimer) {
        clearTimeout(explanationLoadingTimer);
    }

    explanationLoadingTimer = setTimeout(() => {
        if (!signal.aborted) { // Only add if not already aborted
            explanationOutput.classList.add('loading');
            explanationContent.textContent = '';
        }
        explanationLoadingTimer = null; // Timer has done its job or been cleared
    }, 150); // 150ms delay, adjust as needed

        try {
            const response = await fetch('/explain', {
                method: 'POST',
            headers: { 'Content-Type': 'application/json' }, // prettier-ignore
                body: JSON.stringify({ sentence, report_name: currentReportName }),
                signal
            });

            if (signal.aborted) return;

            if (!response.ok) {
            if (explanationLoadingTimer) clearTimeout(explanationLoadingTimer);
            explanationLoadingTimer = null;
            explanationOutput.classList.remove('loading');
                const errorData = await response.json().catch(() => ({ error: `HTTP error ${response.status}` }));
                throw new Error(errorData.error || `HTTP error ${response.status}`);
            }

            const data = await response.json();
            if (signal.aborted) return;

        if (explanationLoadingTimer) clearTimeout(explanationLoadingTimer);
        explanationLoadingTimer = null;
            explanationOutput.classList.remove('loading');
            requestAnimationFrame(() => {
                explanationContent.textContent = data.explanation || "No explanation content received.";
                adjustExplanationPosition();
            });
        } catch (error) {
        if (explanationLoadingTimer) clearTimeout(explanationLoadingTimer);
        explanationLoadingTimer = null;
            explanationOutput.classList.remove('loading');
            if (error.name !== 'AbortError') {
                displayExplanationError(`Explanation Error: ${error.message}`);
            }
        }
    }

    function setLoadingState(isLoading, type = 'all') {
        if (type === 'all' || type === 'report') {
            if (isLoading) {
                if (appLoadingTimeout) {
                    clearTimeout(appLoadingTimeout);
                    appLoadingTimeout = null;
                }
                // Cleanup immediate error/content states
                if (appError) appError.style.display = 'none';
                if (reportImage) reportImage.style.display = 'none';
                if (imageError) imageError.style.display = 'none';
                if (ctImageNote) ctImageNote.style.display = 'none';
                clearExplanationAndLocationUI();

                appLoadingTimeout = setTimeout(() => {
                    if (appLoading) appLoading.style.display = 'block';

                    // Show content-specific loaders only if timeout fires
                    if (reportTextDisplay) {
                        reportTextDisplay.innerHTML = 'Loading...';
                        reportTextDisplay.classList.add('loading');
                        reportTextDisplay.classList.remove('error');
                    }
                    if (imageLoading) imageLoading.style.display = 'block';
                }, 200); // Delay for app and content loading indicators (e.g., 200ms)

            } else {
                if (appLoadingTimeout) {
                    clearTimeout(appLoadingTimeout);
                    appLoadingTimeout = null;
                }
                if (appLoading) appLoading.style.display = 'none';
            }
        }
    }
    function clearAllOutputs(keepReportTextLoading = false) {
        if (!keepReportTextLoading && reportTextDisplay) {
            reportTextDisplay.innerHTML = 'Select a report to view its text.';
            reportTextDisplay.classList.remove('loading', 'error');
        }
        if (reportImage) {
            reportImage.style.display = 'none';
            reportImage.onload = null;
            reportImage.onerror = null;
            reportImage.src = '';
        }
        if (imageError) imageError.style.display = 'none';
        if (ctImageNote) ctImageNote.style.display = 'none';
        clearExplanationAndLocationUI();
        if (appError) appError.style.display = 'none';
        // Reset image modality header on clear
        if (imageModalityHeader) {
             imageModalityHeader.textContent = 'Medical Image'; // Reset to default
        }
    }

    function clearExplanationAndLocationUI() {
        if (explanationContent) {
            explanationContent.textContent = 'Click a sentence to see the explanation here.';
        }
        if (explanationLoadingTimer) { // Clear any pending explanation loading timer
            clearTimeout(explanationLoadingTimer);
            explanationLoadingTimer = null;
        }
        explanationOutput.classList.remove('loading');
        explanationError.style.display = 'none';
        document.querySelectorAll('#report-text-display .selected-sentence').forEach(el => el.classList.remove('selected-sentence'));
    }

    function displayReportTextError(message) {
        reportTextDisplay.innerHTML = `<span class="error-message">${message}</span>`;
        reportTextDisplay.classList.add('error');
        reportTextDisplay.classList.remove('loading');
    }

    function displayAppError(message) {
        appError.textContent = `Error: ${message}`;
        appError.style.display = 'block';
        appLoading.style.display = 'none';
    }

    function displayImageError(message) {
        imageError.textContent = message;
        imageError.style.display = 'block';
        imageLoading.style.display = 'none';
        reportImage.style.display = 'none';
        if (ctImageNote) ctImageNote.style.display = 'none';
    }

    function displayExplanationError(message) {
        explanationError.textContent = message;
        explanationError.style.display = 'block';
        explanationOutput.classList.remove('loading');
        if (explanationContent) explanationContent.textContent = '';
    }

    function setActiveCaseButton(activeButton) {
        if (!caseSelectorTabsContainer) return;
        caseSelectorTabsContainer.querySelectorAll('.nav-button-case').forEach(btn => btn.classList.remove('active'));
        if (activeButton) activeButton.classList.add('active');
    }

    function splitSentences(text) {
        if (!text) return [];
        try {
            if (typeof nlp !== 'function') {
                const basicSentences = text.match(/[^.?!]+[.?!]['"]?(\s+|$)/g);
                return basicSentences ? basicSentences.map(s => s.trim()).filter(s => s.length > 0) : [];
            }
            const doc = nlp(text);
            return doc.sentences().out('array').map(s => s.trim()).filter(s => s.length > 0);
        } catch (e) {
            const basicSentences = text.match(/[^.?!]+[.?!]['"]?(\s+|$)/g);
            return basicSentences ? basicSentences.map(s => s.trim()).filter(s => s.length > 0) : [];
        }
    }

    function adjustExplanationPosition(clickedSentenceElement) {
        const targetSentenceElement = clickedSentenceElement || document.querySelector('#report-text-display .selected-sentence');
        if (!targetSentenceElement) return;

        const explanationSection = explanationOutput.closest('.explanation-section');

        if (explanationOutput && explanationSection && reportSectionDiv) {
            const sentenceRect = targetSentenceElement.getBoundingClientRect();
            const explanationSectionRect = explanationSection.getBoundingClientRect();
            
            // Use actual offsetHeight, fallback if not rendered. Accurate after rAF.
            const explanationHeight = explanationOutput.offsetHeight || 200; 
            
            // Initial top: align with sentence, relative to explanationSection.
            let newTop = sentenceRect.top - explanationSectionRect.top;
            
            // Absolute bottom of explanation box if placed at newTop.
            const explanationBoxAbsoluteBottom = explanationSectionRect.top + newTop + explanationHeight + 15; // 15px margin
            
            const viewportHeight = window.innerHeight;
            const pageBottomOverflow = explanationBoxAbsoluteBottom - viewportHeight;
            
            if (pageBottomOverflow > 0) {
                // Adjust newTop upwards if overflowing viewport bottom.
                newTop -= pageBottomOverflow;
            }
            
            // Prevent top from being negative (relative to its container).
            newTop = Math.max(0, newTop);
            
            explanationOutput.style.top = `${newTop}px`;
        }
    }

    function abortOngoingRequests(excludeTypes = []) {
        if (!excludeTypes.includes('report') && reportLoadAbortController) {
            reportLoadAbortController.abort();
            reportLoadAbortController = null;
        }
        if (!excludeTypes.includes('explain') && explainAbortController) {
            explainAbortController.abort();
            explainAbortController = null;
        }
    }

    initialize();
});


// Make sure this is within your existing DOMContentLoaded listener,
// or wrap it in one if demo.js doesn't have a global one.
document.addEventListener('DOMContentLoaded', () => {

    // ... (any existing JavaScript code in demo.js)

    // --- BEGIN: Immersive Info Dialog Logic ---
    const infoButton = document.getElementById('info-button');
    const immersiveDialogOverlay = document.getElementById('immersive-info-dialog');
    const dialogCloseButton = document.getElementById('dialog-close-button');

    if (infoButton && immersiveDialogOverlay && dialogCloseButton) {
        const openDialog = () => {
            immersiveDialogOverlay.style.display = 'flex'; // Use flex as per CSS
            // Timeout to allow display:flex to apply before triggering transition
            setTimeout(() => {
                immersiveDialogOverlay.classList.add('active');
            }, 10); // Small delay
            document.body.style.overflow = 'hidden'; // Prevent background scroll
        };

        const closeDialog = () => {
            immersiveDialogOverlay.classList.remove('active');
            // Wait for opacity transition to finish before setting display to none
            setTimeout(() => {
                immersiveDialogOverlay.style.display = 'none';
            }, 300); // Must match CSS transition duration
            document.body.style.overflow = ''; // Restore background scroll
        };

        infoButton.addEventListener('click', openDialog);
        dialogCloseButton.addEventListener('click', closeDialog);

        // Dismissible: Close when clicking on the overlay (backdrop)
        immersiveDialogOverlay.addEventListener('click', (event) => {
            if (event.target === immersiveDialogOverlay) {
                closeDialog();
            }
        });

        // Dismissible: Close with Escape key
        document.addEventListener('keydown', (event) => {
            if (event.key === 'Escape' && immersiveDialogOverlay.classList.contains('active')) {
                closeDialog();
            }
        });
    } else {
        // Log errors if elements are not found, helps in debugging
        if (!infoButton) console.error('Dialog trigger button (#info-button) not found.');
        if (!immersiveDialogOverlay) console.error('Immersive dialog (#immersive-info-dialog) not found.');
        if (!dialogCloseButton) console.error('Dialog close button (#dialog-close-button) not found.');
    }
    // --- END: Immersive Info Dialog Logic ---

});