File size: 29,776 Bytes
390cffd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
// Analyzer page functionality
document.addEventListener('DOMContentLoaded', function() {
    initUpload();
    initAnalysis();
    initResults();
    initCreateChallengeModal();
    
    // Check if we should load a sample case
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('sample') === 'true') {
        loadSampleCase();
    }
});

// Upload functionality
function initUpload() {
    const uploadZone = document.getElementById('uploadZone');
    const fileInput = document.getElementById('fileInput');
    const browseButton = document.getElementById('browseButton');
    const filePreview = document.getElementById('filePreview');
    const analyzeBtn = document.getElementById('analyzeBtn');
    const addMoreFilesBtn = document.getElementById('addMoreFiles');
    const clearAllFilesBtn = document.getElementById('clearAllFiles');
    const previewList = document.getElementById('previewList');
    const fileCount = document.getElementById('fileCount');

    // Store selected files
    let selectedFiles = [];

    // Click to upload
    uploadZone.addEventListener('click', () => {
        fileInput.click();
    });

    // Browse button
    if (browseButton) {
        browseButton.addEventListener('click', (e) => {
            e.stopPropagation();
            fileInput.click();
        });
    }

    // Add more files button
    addMoreFilesBtn.addEventListener('click', () => {
        fileInput.click();
    });

    // Clear all files button
    clearAllFilesBtn.addEventListener('click', () => {
        clearAllFiles();
    });

    // File input change (auto-start analysis)
    fileInput.addEventListener('change', (e) => {
        handleFileSelect(e);
        if (getSelectedFiles().length > 0) {
            startAnalysis();
        }
    });

    // Drag and drop
    uploadZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadZone.classList.add('drag-over');
    });

    uploadZone.addEventListener('dragleave', (e) => {
        e.preventDefault();
        uploadZone.classList.remove('drag-over');
    });

    uploadZone.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadZone.classList.remove('drag-over');
        
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            handleFileSelect({ target: { files } });
        }
    });

    // Analyze button
    analyzeBtn.addEventListener('click', startAnalysis);

    function handleFileSelect(e) {
        const files = Array.from(e.target.files);
        if (files.length === 0) return;

        // Validate each file
        const validFiles = [];
        const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/tiff'];
        
        files.forEach(file => {
            // Validate file type
            if (!validTypes.includes(file.type)) {
                window.oncoConnect.showToast(`Invalid file type: ${file.name}. Please upload JPG, PNG, or TIFF files.`, 'error');
                return;
            }

            // Validate file size (max 50MB)
            if (file.size > 50 * 1024 * 1024) {
                window.oncoConnect.showToast(`File too large: ${file.name}. Maximum size is 50MB.`, 'error');
                return;
            }

            validFiles.push(file);
        });

        if (validFiles.length === 0) return;

        // Add valid files to selected files
        selectedFiles = [...selectedFiles, ...validFiles];
        
        // Update UI
        updateFilePreview();
        updateAnalyzeButton();
        
        // Clear file input
        fileInput.value = '';
    }

    function updateFilePreview() {
        if (selectedFiles.length === 0) {
            filePreview.style.display = 'none';
            return;
        }

        filePreview.style.display = 'block';
        
        // Update file count
        fileCount.textContent = `${selectedFiles.length} file${selectedFiles.length > 1 ? 's' : ''}`;
        
        // Clear and rebuild preview list
        previewList.innerHTML = '';
        
        selectedFiles.forEach((file, index) => {
            const previewItem = createFilePreviewItem(file, index);
            previewList.appendChild(previewItem);
        });
    }

    function createFilePreviewItem(file, index) {
        const item = document.createElement('div');
        item.className = 'preview-item';
        item.innerHTML = `
            <div class="preview-icon">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <rect x="3" y="3" width="18" height="18" rx="2" ry="2" stroke="currentColor" stroke-width="2"/>
                    <circle cx="8.5" cy="8.5" r="1.5" stroke="currentColor" stroke-width="2"/>
                    <path d="M21 15L16 10L5 21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
            <div class="preview-details">
                <div class="file-name">${file.name}</div>
                <div class="file-meta">
                    <span class="file-size">${window.oncoConnect.formatFileSize(file.size)}</span>
                    <span class="file-status">Ready to analyze</span>
                </div>
            </div>
            <button class="remove-file" onclick="removeFile(${index})" aria-label="Remove ${file.name}">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <line x1="18" y1="6" x2="6" y2="18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <line x1="6" y1="6" x2="18" y2="18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </button>
        `;
        return item;
    }

    function removeFile(index) {
        selectedFiles.splice(index, 1);
        updateFilePreview();
        updateAnalyzeButton();
    }

    function clearAllFiles() {
        selectedFiles = [];
        updateFilePreview();
        updateAnalyzeButton();
    }

    function updateAnalyzeButton() {
        const analyzeBtn = document.getElementById('analyzeBtn');
        analyzeBtn.disabled = selectedFiles.length === 0;
        
        // Update button text based on file count
        const btnText = analyzeBtn.querySelector('.btn-text');
        if (selectedFiles.length === 0) {
            btnText.textContent = 'Analyze Images';
        } else if (selectedFiles.length === 1) {
            btnText.textContent = 'Analyze Image';
        } else {
            btnText.textContent = `Analyze ${selectedFiles.length} Images`;
        }
    }

    // Make functions globally accessible
    window.removeFile = removeFile;
    window.clearAllFiles = clearAllFiles;
    window.getSelectedFiles = () => selectedFiles;
}

// Analysis functionality
function initAnalysis() {
    // Already initialized in initUpload
}

function startAnalysis() {
    const selectedFiles = window.getSelectedFiles();
    if (!selectedFiles || selectedFiles.length === 0) {
        window.oncoConnect.showToast('Please select at least one image to analyze', 'error');
        return;
    }

    const uploadSection = document.getElementById('uploadSection');
    const loadingSection = document.getElementById('loadingSection');
    const resultsSection = document.getElementById('resultsSection');

    // Hide upload, show loading
    uploadSection.style.display = 'none';
    loadingSection.style.display = 'block';
    resultsSection.style.display = 'none';

    // Show toast with file count
    const fileCount = selectedFiles.length;
    const message = fileCount === 1 ? 'Analysis started...' : `Analysis started for ${fileCount} images...`;
    window.oncoConnect.showToast(message, 'info');

    // Simulate analysis steps with progress bar
    const steps = ['step1', 'step2', 'step3', 'step4'];
    const stepTexts = [
        'Starting analysis...',
        `Processing ${fileCount} image${fileCount > 1 ? 's' : ''}...`,
        'Running AI classification...',
        'Finding clinical trials...'
    ];
    let currentStep = 0;
    const progressFill = document.getElementById('progressFill');
    const progressText = document.getElementById('progressText');

    const progressInterval = setInterval(() => {
        if (currentStep > 0) {
            // Mark previous step as completed
            const prevStep = document.getElementById(steps[currentStep - 1]);
            prevStep.classList.remove('active');
            prevStep.classList.add('completed');
        }
        
        if (currentStep < steps.length) {
            // Activate current step
            const currentStepEl = document.getElementById(steps[currentStep]);
            currentStepEl.classList.add('active');
            
            // Update progress bar
            const progress = ((currentStep + 1) / steps.length) * 100;
            progressFill.style.width = progress + '%';
            progressText.textContent = stepTexts[currentStep];
            
            currentStep++;
        } else {
            clearInterval(progressInterval);
            // Complete the progress bar
            progressFill.style.width = '100%';
            progressText.textContent = 'Analysis complete!';
            
            // Show results after a short delay
            setTimeout(() => {
                showResults();
            }, 1000);
        }
    }, 1200);
}

function showResults() {
    const loadingSection = document.getElementById('loadingSection');
    const resultsSection = document.getElementById('resultsSection');
    const selectedFiles = window.getSelectedFiles();

    loadingSection.style.display = 'none';
    resultsSection.style.display = 'block';

    // Load sample results
    loadResultsData();
    
    // Setup image selector if multiple images
    setupImageSelector(selectedFiles);
    
    // Scroll to results
    resultsSection.scrollIntoView({ behavior: 'smooth' });
}

function setupImageSelector(files) {
    const imageSelector = document.getElementById('imageSelector');
    const imageSelect = document.getElementById('imageSelect');
    
    if (files.length > 1) {
        // Show selector and populate options
        imageSelector.style.display = 'block';
        imageSelect.innerHTML = '';
        
        files.forEach((file, index) => {
            const option = document.createElement('option');
            option.value = index;
            option.textContent = file.name;
            imageSelect.appendChild(option);
        });
        
        // Add change listener
        imageSelect.addEventListener('change', (e) => {
            const selectedIndex = parseInt(e.target.value);
            switchToImage(selectedIndex, files[selectedIndex]);
        });
        
        // Initialize with first image
        switchToImage(0, files[0]);
    } else {
        // Hide selector for single image
        imageSelector.style.display = 'none';
        if (files.length === 1) {
            switchToImage(0, files[0]);
        }
    }
}

function switchToImage(index, file) {
    // Update image info
    document.getElementById('imageFileName').textContent = file.name;
    document.getElementById('imageResolution').textContent = '2048×2048'; // Placeholder
    document.getElementById('analyzedTime').textContent = '2 minutes ago'; // Placeholder
    
    // Update image source (placeholder for now)
    const img = document.getElementById('analyzedImage');
    img.src = URL.createObjectURL(file);
    img.alt = `Analyzed pathology image: ${file.name}`;
    
    // Reinitialize image viewer
    initImageViewer();
}

function loadSampleCase() {
    // Auto-load a sample case for demo with multiple images
    const mockFiles = [
        {
            name: 'sample_breast_wsi_1.jpg',
            size: 2.4 * 1024 * 1024,
            type: 'image/jpeg'
        },
        {
            name: 'sample_breast_wsi_2.jpg',
            size: 1.8 * 1024 * 1024,
            type: 'image/jpeg'
        }
    ];
    
    // Set selected files
    window.getSelectedFiles = () => mockFiles;
    
    // Update UI
    updateFilePreview();
    updateAnalyzeButton();
    
    // Auto-start analysis after a delay
    setTimeout(() => {
        startAnalysis();
    }, 1000);
    
    function updateFilePreview() {
        const filePreview = document.getElementById('filePreview');
        const previewList = document.getElementById('previewList');
        const fileCount = document.getElementById('fileCount');
        
        filePreview.style.display = 'block';
        fileCount.textContent = `${mockFiles.length} files`;
        
        previewList.innerHTML = '';
        mockFiles.forEach((file, index) => {
            const previewItem = createFilePreviewItem(file, index);
            previewList.appendChild(previewItem);
        });
    }
    
    function updateAnalyzeButton() {
        const analyzeBtn = document.getElementById('analyzeBtn');
        analyzeBtn.disabled = false;
        
        const btnText = analyzeBtn.querySelector('.btn-text');
        btnText.textContent = `Analyze ${mockFiles.length} Images`;
    }
    
    function createFilePreviewItem(file, index) {
        const item = document.createElement('div');
        item.className = 'preview-item';
        item.innerHTML = `
            <div class="preview-icon">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <rect x="3" y="3" width="18" height="18" rx="2" ry="2" stroke="currentColor" stroke-width="2"/>
                    <circle cx="8.5" cy="8.5" r="1.5" stroke="currentColor" stroke-width="2"/>
                    <path d="M21 15L16 10L5 21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
            <div class="preview-details">
                <div class="file-name">${file.name}</div>
                <div class="file-meta">
                    <span class="file-size">${window.oncoConnect.formatFileSize(file.size)}</span>
                    <span class="file-status">Ready to analyze</span>
                </div>
            </div>
            <button class="remove-file" onclick="removeFile(${index})" aria-label="Remove ${file.name}">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <line x1="18" y1="6" x2="6" y2="18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <line x1="6" y1="6" x2="18" y2="18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </button>
        `;
        return item;
    }
}

// Results functionality
function initResults() {
    // Save case button
    document.getElementById('saveCase').addEventListener('click', () => {
        requireAuth(saveCase);
    });
    
    // Create challenge button
    document.getElementById('createChallenge').addEventListener('click', () => {
        requireAuth(() => {
            window.oncoConnect.openModal('createChallengeModal');
        });
    });
    
    // Analyze another button
    document.getElementById('analyzeAnother').addEventListener('click', resetAnalyzer);
    
    // Heatmap controls
    initHeatmapControls();
    
    // Trial filters
    initTrialFilters();

    // Export trials
    const exportBtn = document.getElementById('exportTrials');
    if (exportBtn) exportBtn.addEventListener('click', exportTrials);
}

function loadResultsData() {
    // Load analyzed image - use uploaded file if available
    const analyzedImage = document.getElementById('analyzedImage');
    const uploadZone = document.getElementById('uploadZone');
    
    if (uploadZone.selectedFile) {
        // Use the actual uploaded file
        const reader = new FileReader();
        reader.onload = function(e) {
            analyzedImage.src = e.target.result;
        };
        reader.readAsDataURL(uploadZone.selectedFile);
        
        // Update image info
        document.getElementById('imageFileName').textContent = uploadZone.selectedFile.name;
        document.getElementById('imageResolution').textContent = '2048×2048'; // Mock resolution
    } else {
        // Use placeholder for demo
        analyzedImage.src = createPlaceholderImage(400, 400, '#f8fafc', '🔬 Pathology Image');
        document.getElementById('imageFileName').textContent = 'sample_breast_wsi.jpg';
        document.getElementById('imageResolution').textContent = '2048×2048';
    }
    
    // Update analyzed time
    document.getElementById('analyzedTime').textContent = 'Just now';
    
    // Create heatmap overlay
    createHeatmapOverlay();
    
    // Set diagnosis results
    document.getElementById('cancerStatus').textContent = 'Yes';
    document.getElementById('confidenceValue').textContent = '94.2%';
    document.getElementById('diagnosisExplanation').textContent = 
        'Analysis indicates invasive ductal carcinoma with well-defined tumor boundaries. High cellular density and irregular nuclear morphology support malignant classification.';
    
    // Set chemo response
    document.getElementById('chemoResponse').textContent = 'Likely Responsive';
    document.getElementById('chemoExplanation').textContent = 
        'Tumor characteristics suggest good response to standard chemotherapy protocols. High proliferation markers and hormone receptor status indicate favorable treatment outcomes.';

    // Update risk assessment demo
    updateRiskAssessment(87);
    
    // Load clinical trials
    loadClinicalTrials();
    
    // Initialize image viewer controls
    initImageViewer();
}

function updateRiskAssessment(score) {
    const riskScoreEl = document.getElementById('riskScore');
    const riskBadgeEl = document.getElementById('riskBadge');
    const riskCategoryEl = document.getElementById('riskCategory');
    if (!riskScoreEl || !riskBadgeEl || !riskCategoryEl) return;

    riskScoreEl.textContent = String(score);
    let riskLevel, riskClass;
    if (score >= 70) { riskLevel = 'HIGH RISK'; riskClass = 'high-risk'; }
    else if (score >= 40) { riskLevel = 'MEDIUM RISK'; riskClass = 'medium-risk'; }
    else { riskLevel = 'LOW RISK'; riskClass = 'low-risk'; }

    riskBadgeEl.textContent = riskLevel;
    riskBadgeEl.className = 'card-badge ' + riskClass;
    riskCategoryEl.textContent = riskLevel;
}

function createPlaceholderImage(width, height, color, text) {
    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    
    const ctx = canvas.getContext('2d');
    ctx.fillStyle = color;
    ctx.fillRect(0, 0, width, height);
    
    // Add some pattern to simulate pathology image
    ctx.strokeStyle = '#e2e8f0';
    ctx.lineWidth = 1;
    
    // Create a grid pattern
    for (let i = 0; i < width; i += 20) {
        for (let j = 0; j < height; j += 20) {
            if (Math.random() > 0.7) {
                ctx.fillStyle = '#e2e8f0';
                ctx.fillRect(i, j, 15, 15);
            }
        }
    }
    
    // Add text
    ctx.fillStyle = '#9ca3af';
    ctx.font = '20px sans-serif';
    ctx.textAlign = 'center';
    ctx.fillText(text, width/2, height/2);
    
    return canvas.toDataURL();
}

function createHeatmapOverlay() {
    const canvas = document.getElementById('heatmapOverlay');
    const ctx = canvas.getContext('2d');
    
    canvas.width = 400;
    canvas.height = 400;
    
    // Create random heatmap pattern
    const gradient = ctx.createRadialGradient(200, 200, 0, 200, 200, 150);
    gradient.addColorStop(0, 'rgba(255, 0, 0, 0.8)');
    gradient.addColorStop(0.5, 'rgba(255, 255, 0, 0.6)');
    gradient.addColorStop(1, 'rgba(255, 0, 0, 0)');
    
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, 400, 400);
    
    // Add some random hot spots
    for (let i = 0; i < 5; i++) {
        const x = Math.random() * 400;
        const y = Math.random() * 400;
        const radius = Math.random() * 30 + 20;
        
        const spotGradient = ctx.createRadialGradient(x, y, 0, x, y, radius);
        spotGradient.addColorStop(0, 'rgba(255, 0, 0, 0.9)');
        spotGradient.addColorStop(1, 'rgba(255, 0, 0, 0)');
        
        ctx.fillStyle = spotGradient;
        ctx.beginPath();
        ctx.arc(x, y, radius, 0, 2 * Math.PI);
        ctx.fill();
    }
}

function initImageViewer() {
    const zoomInBtn = document.getElementById('zoomIn');
    const zoomOutBtn = document.getElementById('zoomOut');
    const fitScreenBtn = document.getElementById('fitScreen');
    const downloadOverlayBtn = document.getElementById('downloadOverlay');
    const analyzedImage = document.getElementById('analyzedImage');
    
    let currentZoom = 1;
    const minZoom = 0.5;
    const maxZoom = 3;
    const zoomStep = 0.2;
    
    zoomInBtn.addEventListener('click', () => {
        currentZoom = Math.min(currentZoom + zoomStep, maxZoom);
        updateImageZoom();
    });
    
    zoomOutBtn.addEventListener('click', () => {
        currentZoom = Math.max(currentZoom - zoomStep, minZoom);
        updateImageZoom();
    });
    
    fitScreenBtn.addEventListener('click', () => {
        currentZoom = 1;
        updateImageZoom();
    });
    
    downloadOverlayBtn.addEventListener('click', () => {
        downloadHeatmap();
    });
    
    function updateImageZoom() {
        analyzedImage.style.transform = `scale(${currentZoom})`;
        analyzedImage.style.transformOrigin = 'center';
    }
    
    function downloadHeatmap() {
        const canvas = document.getElementById('heatmapOverlay');
        const link = document.createElement('a');
        link.download = 'heatmap-overlay.png';
        link.href = canvas.toDataURL();
        link.click();
        window.oncoConnect.showToast('Heatmap downloaded successfully!', 'success');
    }
}

function initHeatmapControls() {
    const heatmapToggle = document.getElementById('heatmapToggle');
    const opacitySlider = document.getElementById('opacitySlider');
    const opacityValue = document.getElementById('opacityValue');
    const heatmapOverlay = document.getElementById('heatmapOverlay');
    
    // Initialize heatmap visibility
    updateHeatmapVisibility();
    
    heatmapToggle.addEventListener('change', () => {
        updateHeatmapVisibility();
    });
    
    opacitySlider.addEventListener('input', () => {
        const opacity = opacitySlider.value / 100;
        heatmapOverlay.style.opacity = opacity;
        opacityValue.textContent = opacitySlider.value + '%';
    });
}

function updateHeatmapVisibility() {
    const heatmapToggle = document.getElementById('heatmapToggle');
    const heatmapOverlay = document.getElementById('heatmapOverlay');
    const analyzedImage = document.getElementById('analyzedImage');
    
    if (heatmapToggle.checked) {
        // Show both image and heatmap overlay
        analyzedImage.style.display = 'block';
        heatmapOverlay.style.display = 'block';
    } else {
        // Show only the uploaded image
        analyzedImage.style.display = 'block';
        heatmapOverlay.style.display = 'none';
    }
}

function initTrialFilters() {
    const filterChips = document.querySelectorAll('.filter-chip');
    filterChips.forEach(chip => {
        chip.addEventListener('click', () => {
            const group = chip.parentElement;
            
            // Remove active from siblings
            group.querySelectorAll('.filter-chip').forEach(sibling => {
                sibling.classList.remove('active');
            });
            
            // Add active to clicked chip
            chip.classList.add('active');
            
            // Filter trials
            filterTrials();
        });
    });
}

function filterTrials() {
    const activePhase = document.querySelector('.filter-chip[data-phase].active')?.dataset.phase || 'all';
    const activeStatus = document.querySelector('.filter-chip[data-status].active')?.dataset.status || 'all';
    const activeDistance = document.querySelector('.filter-chip[data-distance].active')?.dataset.distance || 'all';
    const activeBiomarker = document.querySelector('.filter-chip[data-biomarker].active')?.dataset.biomarker || 'all';
    
    const trialCards = document.querySelectorAll('.trial-card');
    
    trialCards.forEach(card => {
        const phase = card.dataset.phase;
        const status = card.dataset.status;
        const distance = card.dataset.distance || 'remote';
        const biomarkers = (card.dataset.biomarkers || '').split(',');

        const phaseMatch = activePhase === 'all' || phase === activePhase;
        const statusMatch = activeStatus === 'all' || status === activeStatus;
        const distanceMatch = activeDistance === 'all' || distance === activeDistance;
        const biomarkerMatch = activeBiomarker === 'all' || biomarkers.includes(activeBiomarker);
        
        card.style.display = (phaseMatch && statusMatch && distanceMatch && biomarkerMatch) ? 'block' : 'none';
    });
}

function loadClinicalTrials() {
    const trialsList = document.getElementById('trialsList');
    const trials = window.oncoConnect.getClinicalTrials();
    
    trialsList.innerHTML = trials.map(trial => `
        <div class="trial-card"
             data-phase="${trial.phase.split(' ')[1]}"
             data-status="${trial.status.toLowerCase()}"
             data-distance="${trial.distance || 'remote'}"
             data-biomarkers="${(trial.biomarkers || []).join(',')}">
            <div class="trial-header">
                <h3 class="trial-title">${trial.title}</h3>
                <div class="trial-badges">
                    <span class="trial-badge phase">${trial.phase}</span>
                    <span class="trial-badge status ${trial.status.toLowerCase()}">${trial.status}</span>
                </div>
            </div>
            <div class="trial-description">${trial.description}</div>
            <div class="trial-details">
                <div class="trial-detail">
                    <span class="detail-label">Inclusion:</span>
                    <span class="detail-value">${trial.inclusion}</span>
                </div>
                <div class="trial-detail">
                    <span class="detail-label">Site:</span>
                    <span class="detail-value">${trial.location}</span>
                </div>
                <div class="trial-detail">
                    <span class="detail-label">Contact:</span>
                    <span class="detail-value">${trial.contact}</span>
                </div>
            </div>
        </div>
    `).join('');
}

function saveCase() {
    const caseData = {
        id: window.oncoConnect.generateId(),
        fileName: document.getElementById('fileName').textContent,
        diagnosis: document.getElementById('cancerStatus').textContent,
        confidence: document.getElementById('confidenceValue').textContent,
        timestamp: new Date().toISOString(),
        chemoResponse: document.getElementById('chemoResponse').textContent
    };
    
    // Save to localStorage
    const savedCases = window.oncoConnect.getSavedData('savedCases') || [];
    savedCases.push(caseData);
    window.oncoConnect.saveData('savedCases', savedCases);
    
    window.oncoConnect.showToast('Case saved successfully!');
}

function resetAnalyzer() {
    document.getElementById('uploadSection').style.display = 'block';
    document.getElementById('loadingSection').style.display = 'none';
    document.getElementById('resultsSection').style.display = 'none';
    
    // Clear file input
    document.getElementById('fileInput').value = '';
    document.getElementById('filePreview').style.display = 'none';
    document.getElementById('analyzeBtn').disabled = true;
    
    // Scroll to top
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

// Create Challenge Modal functionality
function initCreateChallengeModal() {
    const modal = document.getElementById('createChallengeModal');
    const form = document.getElementById('challengeForm');
    const closeBtn = document.getElementById('closeChallengeModal');
    const cancelBtn = document.getElementById('cancelChallenge');
    
    closeBtn.addEventListener('click', () => {
        window.oncoConnect.closeModal(modal);
    });
    
    cancelBtn.addEventListener('click', () => {
        window.oncoConnect.closeModal(modal);
    });
    
    form.addEventListener('submit', (e) => {
        e.preventDefault();
        createChallenge();
    });
}

function createChallenge() {
    const title = document.getElementById('challengeTitle').value;
    const description = document.getElementById('challengeDescription').value;
    const difficulty = document.getElementById('challengeDifficulty').value;
    
    const challengeData = {
        id: window.oncoConnect.generateId(),
        title,
        description,
        difficulty,
        solved: 0,
        enrolled: true,
        createdBy: 'user',
        timestamp: new Date().toISOString()
    };
    
    // Add to challenges
    const challenges = window.oncoConnect.getSavedData('challenges') || [];
    challenges.push(challengeData);
    window.oncoConnect.saveData('challenges', challenges);
    
    // Close modal and show success
    window.oncoConnect.closeModal('createChallengeModal');
    window.oncoConnect.showToast('Challenge created successfully!');
    
    // Reset form
    document.getElementById('challengeForm').reset();
}