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
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
class PotatoDiseaseDetector {
    constructor() {
        this.currentMethod = 'upload';
        this.stream = null;
        this.selectedFile = null;
        this.initializeElements();
        this.checkBrowserCompatibility();
        this.bindEvents();
    }

    checkBrowserCompatibility() {
        // Check for File System Access API support
        this.folderSelectionSupported = 'showSaveFilePicker' in window;
        
        // Update download help text based on browser compatibility
        const downloadHelp = document.getElementById('downloadHelp');
        if (downloadHelp) {
            if (this.folderSelectionSupported) {
                downloadHelp.innerHTML = 'βœ… Folder selection supported - Choose where to save your PDF!';
                downloadHelp.style.color = '#28a745';
            } else {
                downloadHelp.innerHTML = 'πŸ“ Will download to your default Downloads folder';
                downloadHelp.style.color = '#6c757d';
            }
        }
        
        // Update button text based on compatibility
        const downloadBtn = document.getElementById('downloadResultBtn');
        if (downloadBtn && this.folderSelectionSupported) {
            downloadBtn.innerHTML = '<i class="fas fa-folder-open"></i> Choose Folder & Download PDF';
        } else if (downloadBtn) {
            downloadBtn.innerHTML = '<i class="fas fa-download"></i> Download PDF Report';
        }
        
        console.log('Browser compatibility:', {
            folderSelection: this.folderSelectionSupported,
            userAgent: navigator.userAgent
        });
    }

    initializeElements() {
        // Method cards
        this.uploadCard = document.getElementById('uploadCard');
        this.cameraCard = document.getElementById('cameraCard');
        
        // Sections
        this.uploadSection = document.getElementById('uploadSection');
        this.cameraSection = document.getElementById('cameraSection');
        
        // Upload elements
        this.uploadArea = document.getElementById('uploadArea');
        this.fileInput = document.getElementById('fileInput');
        
        // Camera elements
        this.video = document.getElementById('video');
        this.canvas = document.getElementById('canvas');
        this.startCameraBtn = document.getElementById('startCamera');
        this.captureBtn = document.getElementById('captureBtn');
        this.stopCameraBtn = document.getElementById('stopCamera');
        
        // Preview and actions
        this.imagePreview = document.getElementById('imagePreview');
        this.previewImg = document.getElementById('previewImg');
        this.predictBtn = document.getElementById('predictBtn');
        this.clearBtn = document.getElementById('clearBtn');
        
        // Results
        this.resultsSection = document.getElementById('resultsSection');
        this.loadingOverlay = document.getElementById('loadingOverlay');
        this.newAnalysisBtn = document.getElementById('newAnalysisBtn');
        this.downloadResultBtn = document.getElementById('downloadResultBtn');
        
        // Analyzed image display
        this.analyzedImageSection = document.getElementById('analyzedImageSection');
        this.analyzedImage = document.getElementById('analyzedImage');
        
        // Result elements
        this.diseaseName = document.getElementById('diseaseName');
        this.diseaseDescription = document.getElementById('diseaseDescription');
        this.confidenceValue = document.getElementById('confidenceValue');
        this.confidenceBadge = document.getElementById('confidenceBadge');
        this.diseaseIcon = document.getElementById('diseaseIcon');
        this.timestamp = document.getElementById('timestamp');
        this.probabilities = document.getElementById('probabilities');
        this.recommendationList = document.getElementById('recommendationList');
    }

    bindEvents() {
        // Method switching
        this.uploadCard.addEventListener('click', () => this.switchMethod('upload'));
        this.cameraCard.addEventListener('click', () => this.switchMethod('camera'));
        
        // Upload events with touch support
        this.uploadArea.addEventListener('click', (e) => {
            console.log('Upload area clicked');
            this.fileInput.click();
        });
        
        // Touch events for mobile
        this.uploadArea.addEventListener('touchend', (e) => {
            e.preventDefault();
            console.log('Upload area touched');
            this.fileInput.click();
        });
        
        // Specific handler for browse text
        const browseText = document.querySelector('.browse-text');
        if (browseText) {
            browseText.addEventListener('click', (e) => {
                e.stopPropagation();
                console.log('Browse text clicked');
                this.fileInput.click();
            });
            
            browseText.addEventListener('touchend', (e) => {
                e.preventDefault();
                e.stopPropagation();
                console.log('Browse text touched');
                this.fileInput.click();
            });
        }
        
        this.uploadArea.addEventListener('dragover', this.handleDragOver.bind(this));
        this.uploadArea.addEventListener('dragleave', this.handleDragLeave.bind(this));
        this.uploadArea.addEventListener('drop', this.handleDrop.bind(this));
        this.fileInput.addEventListener('change', (e) => {
            console.log('File input changed:', e.target.files);
            this.handleFileSelect(e);
        });
        
        // Camera events
        this.startCameraBtn.addEventListener('click', this.startCamera.bind(this));
        this.captureBtn.addEventListener('click', this.capturePhoto.bind(this));
        this.stopCameraBtn.addEventListener('click', this.stopCamera.bind(this));
        
        // Action buttons
        this.predictBtn.addEventListener('click', this.makePrediction.bind(this));
        this.clearBtn.addEventListener('click', this.clearSelection.bind(this));
        this.newAnalysisBtn.addEventListener('click', this.newAnalysis.bind(this));
        this.downloadResultBtn.addEventListener('click', this.downloadReport.bind(this));
    }

    switchMethod(method) {
        this.currentMethod = method;
        
        // Update card states
        this.uploadCard.classList.toggle('active', method === 'upload');
        this.cameraCard.classList.toggle('active', method === 'camera');
        
        // Show/hide sections
        this.uploadSection.style.display = method === 'upload' ? 'block' : 'none';
        this.cameraSection.style.display = method === 'camera' ? 'block' : 'none';
        
        // Stop camera if switching away
        if (method !== 'camera') {
            this.stopCamera();
        }
        
        // Clear any existing selections
        this.clearSelection();
    }

    // Upload handling
    handleDragOver(e) {
        e.preventDefault();
        this.uploadArea.classList.add('dragover');
    }

    handleDragLeave(e) {
        e.preventDefault();
        this.uploadArea.classList.remove('dragover');
    }

    handleDrop(e) {
        e.preventDefault();
        this.uploadArea.classList.remove('dragover');
        
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            this.processFile(files[0]);
        }
    }

    handleFileSelect(e) {
        const file = e.target.files[0];
        if (file) {
            this.processFile(file);
        }
    }

    processFile(file) {
        console.log('Processing file:', file.name, file.type, file.size);
        
        if (!this.isValidImageFile(file)) {
            this.showError('Please select a valid image file (PNG, JPG, JPEG)');
            return;
        }

        if (file.size > 16 * 1024 * 1024) {
            this.showError('File size must be less than 16MB');
            return;
        }

        this.selectedFile = file;
        console.log('File selected successfully:', file.name);
        this.displayImagePreview(file);
    }

    isValidImageFile(file) {
        const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
        return validTypes.includes(file.type);
    }

    displayImagePreview(file) {
        const reader = new FileReader();
        reader.onload = (e) => {
            this.previewImg.src = e.target.result;
            this.imagePreview.style.display = 'block';
            this.imagePreview.classList.add('fade-in');
            this.hideResults();
        };
        reader.readAsDataURL(file);
    }

    // Camera handling
    async startCamera() {
        try {
            // Enhanced camera constraints for mobile devices
            const constraints = {
                video: {
                    facingMode: 'environment', // Use back camera on mobile
                    width: { ideal: 1280, max: 1920 },
                    height: { ideal: 720, max: 1080 },
                    aspectRatio: { ideal: 16/9 }
                }
            };
            
            // Fallback for devices that don't support environment camera
            try {
                this.stream = await navigator.mediaDevices.getUserMedia(constraints);
            } catch (envError) {
                console.log('Environment camera not available, trying default camera');
                const fallbackConstraints = {
                    video: {
                        width: { ideal: 1280, max: 1920 },
                        height: { ideal: 720, max: 1080 }
                    }
                };
                this.stream = await navigator.mediaDevices.getUserMedia(fallbackConstraints);
            }
            
            this.video.srcObject = this.stream;
            this.video.style.display = 'block';
            
            this.startCameraBtn.style.display = 'none';
            this.captureBtn.style.display = 'inline-flex';
            this.stopCameraBtn.style.display = 'inline-flex';
            
        } catch (error) {
            console.error('Error accessing camera:', error);
            this.showError('Could not access camera. Please check permissions.');
        }
    }

    capturePhoto() {
        const context = this.canvas.getContext('2d');
        this.canvas.width = this.video.videoWidth;
        this.canvas.height = this.video.videoHeight;
        
        context.drawImage(this.video, 0, 0);
        
        this.canvas.toBlob((blob) => {
            this.selectedFile = blob;
            this.previewImg.src = this.canvas.toDataURL();
            this.imagePreview.style.display = 'block';
            this.imagePreview.classList.add('fade-in');
            this.hideResults();
        }, 'image/png');
    }

    stopCamera() {
        if (this.stream) {
            this.stream.getTracks().forEach(track => track.stop());
            this.stream = null;
        }
        
        this.video.style.display = 'none';
        this.startCameraBtn.style.display = 'inline-flex';
        this.captureBtn.style.display = 'none';
        this.stopCameraBtn.style.display = 'none';
    }

    // Prediction
    async makePrediction() {
        console.log('Making prediction...');
        console.log('Current method:', this.currentMethod);
        console.log('Selected file:', this.selectedFile);
        
        if (!this.selectedFile) {
            this.showError('Please select an image first');
            return;
        }

        this.showLoading(true);
        
        try {
            let response;
            
            if (this.currentMethod === 'camera') {
                console.log('Using camera prediction endpoint');
                // Send base64 image for camera
                const imageData = this.canvas.toDataURL();
                response = await fetch('/predict_camera', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ image: imageData })
                });
            } else {
                console.log('Using upload prediction endpoint');
                // Send file for upload
                const formData = new FormData();
                formData.append('file', this.selectedFile);
                
                console.log('FormData created with file:', this.selectedFile.name);
                
                response = await fetch('/predict', {
                    method: 'POST',
                    body: formData
                });
            }

            console.log('Response status:', response.status);
            
            if (!response.ok) {
                const errorText = await response.text();
                console.error('Response error:', errorText);
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            console.log('Prediction result:', result);
            
            if (result.error) {
                throw new Error(result.error);
            }

            this.displayResults(result);
            
        } catch (error) {
            console.error('Prediction error:', error);
            this.showError(`Prediction failed: ${error.message}`);
        } finally {
            this.showLoading(false);
        }
    }

    displayResults(result) {
        // Store current prediction data for PDF generation
        this.currentPredictionData = result;
        
        // Display the analyzed image if available
        if (result.image_url) {
            this.analyzedImage.src = result.image_url;
            this.analyzedImageSection.style.display = 'block';
        }
        
        // Update main prediction
        this.diseaseName.textContent = result.predicted_class;
        this.diseaseDescription.textContent = result.description;
        this.confidenceValue.textContent = `${result.confidence}%`;
        this.timestamp.textContent = `Analysis completed: ${result.timestamp}`;
        
        // Update confidence badge color
        this.updateConfidenceBadge(result.confidence);
        
        // Update disease icon
        this.updateDiseaseIcon(result.predicted_class);
        
        // Display probabilities
        this.displayProbabilities(result.all_predictions);
        
        // Display recommendations
        this.displayRecommendations(result.recommendations);
        
        // Show results
        this.resultsSection.style.display = 'block';
        this.resultsSection.classList.add('fade-in');
        this.resultsSection.scrollIntoView({ behavior: 'smooth' });
    }

    updateConfidenceBadge(confidence) {
        if (confidence >= 90) {
            this.confidenceBadge.style.background = 'linear-gradient(135deg, #22c55e, #16a34a)';
        } else if (confidence >= 70) {
            this.confidenceBadge.style.background = 'linear-gradient(135deg, #f59e0b, #d97706)';
        } else {
            this.confidenceBadge.style.background = 'linear-gradient(135deg, #ef4444, #dc2626)';
        }
    }

    updateDiseaseIcon(diseaseName) {
        const iconMap = {
            'Early Blight': { icon: 'fas fa-exclamation-triangle', color: '#f59e0b' },
            'Late Blight': { icon: 'fas fa-skull-crossbones', color: '#ef4444' },
            'Healthy': { icon: 'fas fa-check-circle', color: '#22c55e' }
        };
        
        const iconInfo = iconMap[diseaseName] || { icon: 'fas fa-leaf', color: '#667eea' };
        this.diseaseIcon.innerHTML = `<i class="${iconInfo.icon}"></i>`;
        this.diseaseIcon.style.color = iconInfo.color;
    }

    displayProbabilities(allPredictions) {
        this.probabilities.innerHTML = '';
        
        Object.entries(allPredictions).forEach(([disease, data]) => {
            const probability = data.probability;
            const item = document.createElement('div');
            item.className = 'probability-item';
            
            const color = this.getProbabilityColor(probability);
            
            item.innerHTML = `
                <div class="probability-label">${disease}</div>
                <div class="probability-bar">
                    <div class="probability-fill" style="width: ${probability}%; background: ${color};"></div>
                </div>
                <div class="probability-value">${probability}%</div>
            `;
            
            this.probabilities.appendChild(item);
        });
    }

    getProbabilityColor(probability) {
        if (probability >= 70) return 'linear-gradient(90deg, #22c55e, #16a34a)';
        if (probability >= 40) return 'linear-gradient(90deg, #f59e0b, #d97706)';
        return 'linear-gradient(90deg, #ef4444, #dc2626)';
    }

    displayRecommendations(recommendations) {
        this.recommendationList.innerHTML = '';
        
        recommendations.forEach((rec, index) => {
            const item = document.createElement('div');
            item.className = 'recommendation-item';
            item.innerHTML = `
                <i class="fas fa-check-circle"></i>
                <span>${rec}</span>
            `;
            this.recommendationList.appendChild(item);
        });
    }

    // Utility methods
    clearSelection() {
        this.selectedFile = null;
        this.fileInput.value = '';
        this.imagePreview.style.display = 'none';
        this.hideResults();
    }

    newAnalysis() {
        this.clearSelection();
        this.stopCamera();
        this.switchMethod('upload');
    }

    hideResults() {
        this.resultsSection.style.display = 'none';
        this.analyzedImageSection.style.display = 'none';
    }

    showLoading(show) {
        this.loadingOverlay.style.display = show ? 'flex' : 'none';
    }

    showError(message) {
        alert(`Error: ${message}`);
    }

    async downloadReport() {
        try {
            // Show loading state
            this.downloadResultBtn.disabled = true;
            
            if (this.folderSelectionSupported) {
                this.downloadResultBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Preparing folder selection...';
            } else {
                this.downloadResultBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating PDF...';
            }
            
            // Gather all report data
            const reportData = {
                predicted_class: this.diseaseName.textContent,
                confidence: parseFloat(this.confidenceValue.textContent.replace('%', '')),
                description: this.diseaseDescription.textContent,
                timestamp: this.timestamp.textContent,
                image_url: this.analyzedImage.src || null,
                all_predictions: this.currentPredictionData || {},
                recommendations: this.getCurrentRecommendations()
            };
            
            // Try to generate PDF via backend
            const response = await fetch('/generate-pdf-report', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(reportData)
            });
            
            if (response.ok) {
                // Backend PDF generation successful
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                
                // Create download link with File System Access API for folder selection
                if (this.folderSelectionSupported) {
                    this.downloadResultBtn.innerHTML = '<i class="fas fa-folder-open"></i> Choose save location...';
                    
                    try {
                        // Modern browsers with File System Access API
                        const timestamp = new Date().toISOString().slice(0, 19).replace(/[-:]/g, '');
                        const diseaseName = reportData.predicted_class.replace(/\s+/g, '_');
                        const filename = `potato_disease_report_${diseaseName}_${timestamp}.pdf`;
                        
                        // Show folder picker dialog
                        const fileHandle = await window.showSaveFilePicker({
                            suggestedName: filename,
                            types: [
                                {
                                    description: 'PDF Reports',
                                    accept: {
                                        'application/pdf': ['.pdf'],
                                    },
                                },
                            ],
                            excludeAcceptAllOption: true,
                            startIn: 'documents' // Suggest Documents folder
                        });
                        
                        this.downloadResultBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving to selected folder...';
                        
                        const writable = await fileHandle.createWritable();
                        await writable.write(blob);
                        await writable.close();
                        
                        this.showSuccessMessage('πŸ“ PDF report saved to your chosen folder successfully!');
                    } catch (err) {
                        if (err.name === 'AbortError') {
                            // User cancelled folder selection
                            this.showInfoMessage('πŸ“ Folder selection cancelled. Try again to choose a save location.');
                        } else {
                            console.error('Folder save error:', err);
                            // Fallback to regular download
                            this.fallbackDownload(url, blob, reportData);
                            this.showWarningMessage('πŸ“ Folder selection failed. Downloaded to default location instead.');
                        }
                    }
                } else {
                    // Fallback for browsers without File System Access API
                    this.fallbackDownload(url, blob, reportData);
                }
                
                window.URL.revokeObjectURL(url);
            } else {
                // Backend failed, check if it's a server-side issue or ReportLab missing
                let errorData;
                try {
                    errorData = await response.json();
                } catch (e) {
                    errorData = { error: 'Unknown server error' };
                }
                
                console.warn('Backend PDF generation failed:', errorData);
                
                if (errorData.fallback === 'client' || response.status === 503) {
                    // Server suggests client-side fallback
                    console.log('Using client-side PDF generation fallback');
                    await this.generateClientSidePDF(reportData);
                } else {
                    // Other server errors
                    throw new Error(errorData.message || errorData.error || 'Server PDF generation failed');
                }
            }
            
        } catch (error) {
            console.error('Error downloading report:', error);
            // Final fallback to text report
            this.generateTextReport();
            this.showErrorMessage('PDF generation failed, downloaded as text file instead.');
        } finally {
            // Reset button state
            this.downloadResultBtn.disabled = false;
            
            if (this.folderSelectionSupported) {
                this.downloadResultBtn.innerHTML = '<i class="fas fa-folder-open"></i> Choose Folder & Download PDF';
            } else {
                this.downloadResultBtn.innerHTML = '<i class="fas fa-download"></i> Download PDF Report';
            }
        }
    }
    
    fallbackDownload(url, blob, reportData) {
        const timestamp = new Date().toISOString().slice(0, 19).replace(/[-:]/g, '');
        const diseaseName = reportData.predicted_class.replace(/\s+/g, '_');
        const filename = `potato_disease_report_${diseaseName}_${timestamp}.pdf`;
        
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        
        this.showSuccessMessage('PDF report downloaded to default folder!');
    }
    
    async generateClientSidePDF(reportData) {
        // Client-side PDF generation using jsPDF
        try {
            if (typeof jsPDF === 'undefined') {
                throw new Error('jsPDF library not loaded');
            }
            
            console.log('πŸ“„ Generating client-side PDF...');
            const { jsPDF } = window.jspdf;
            const doc = new jsPDF();
            
            // Add content to PDF
            doc.setFontSize(20);
            doc.text('πŸ₯” POTATO DISEASE DETECTION REPORT', 20, 30);
            
            doc.setFontSize(12);
            doc.text(`Report Generated: ${reportData.timestamp}`, 20, 50);
            doc.text(`Analysis Method: Deep Learning AI Classification`, 20, 60);
            doc.text(`Model Version: TensorFlow/Keras CNN v1.0`, 20, 70);
            
            // Main diagnosis
            doc.setFontSize(16);
            doc.text('🎯 DIAGNOSIS RESULTS', 20, 90);
            
            doc.setFontSize(12);
            doc.text(`Predicted Disease: ${reportData.predicted_class}`, 20, 105);
            doc.text(`Confidence: ${reportData.confidence}%`, 20, 115);
            
            // Risk assessment
            let riskLevel = 'Unknown';
            if (reportData.confidence >= 80) riskLevel = 'High Confidence';
            else if (reportData.confidence >= 60) riskLevel = 'Medium Confidence';
            else riskLevel = 'Low Confidence - Manual Verification Recommended';
            
            doc.text(`Risk Assessment: ${riskLevel}`, 20, 125);
            
            // Description
            doc.setFontSize(16);
            doc.text('πŸ“‹ DESCRIPTION', 20, 145);
            
            doc.setFontSize(10);
            const splitDescription = doc.splitTextToSize(reportData.description, 170);
            doc.text(splitDescription, 20, 160);
            
            let yPos = 160 + (splitDescription.length * 5) + 15;
            
            // Probability breakdown
            doc.setFontSize(16);
            doc.text('πŸ“Š PROBABILITY BREAKDOWN', 20, yPos);
            yPos += 15;
            
            doc.setFontSize(10);
            if (reportData.all_predictions) {
                for (const [disease, info] of Object.entries(reportData.all_predictions)) {
                    doc.text(`β€’ ${disease}: ${info.probability}%`, 20, yPos);
                    yPos += 10;
                }
            }
            
            yPos += 10;
            
            // Recommendations
            doc.setFontSize(16);
            doc.text('πŸ’‘ TREATMENT RECOMMENDATIONS', 20, yPos);
            yPos += 15;
            
            doc.setFontSize(10);
            reportData.recommendations.forEach((rec, index) => {
                const recText = `${index + 1}. ${rec}`;
                const splitRec = doc.splitTextToSize(recText, 170);
                doc.text(splitRec, 20, yPos);
                yPos += splitRec.length * 5 + 3;
                
                // Add new page if needed
                if (yPos > 270) {
                    doc.addPage();
                    yPos = 20;
                }
            });
            
            // Footer
            yPos = Math.max(yPos + 20, 250);
            doc.setFontSize(8);
            doc.text('Generated by Potato Disease Detection System', 20, yPos);
            doc.text('Powered by Flask & TensorFlow | Lucky Sharma', 20, yPos + 8);
            doc.text('Β© 2025 All Rights Reserved', 20, yPos + 16);
            
            // Save PDF
            const timestamp = new Date().toISOString().slice(0, 19).replace(/[-:]/g, '');
            const diseaseName = reportData.predicted_class.replace(/\s+/g, '_');
            const filename = `potato_disease_report_${diseaseName}_${timestamp}.pdf`;
            
            // Try to use File System Access API for folder selection
            if ('showSaveFilePicker' in window) {
                try {
                    const fileHandle = await window.showSaveFilePicker({
                        suggestedName: filename,
                        types: [
                            {
                                description: 'PDF files',
                                accept: {
                                    'application/pdf': ['.pdf'],
                                },
                            },
                        ],
                    });
                    
                    const writable = await fileHandle.createWritable();
                    const pdfBlob = doc.output('blob');
                    await writable.write(pdfBlob);
                    await writable.close();
                    
                    this.showSuccessMessage('PDF report saved successfully using client-side generation!');
                } catch (err) {
                    if (err.name !== 'AbortError') {
                        // Fallback to regular download
                        doc.save(filename);
                        this.showSuccessMessage('PDF report generated successfully!');
                    }
                }
            } else {
                // Regular download for older browsers
                doc.save(filename);
                this.showSuccessMessage('PDF report generated successfully!');
            }
            
        } catch (error) {
            console.error('Client-side PDF generation failed:', error);
            this.showErrorMessage('PDF generation failed. Falling back to text report.');
            this.generateTextReport();
        }
    }
    
    getCurrentRecommendations() {
        const recommendations = [];
        const recItems = this.recommendationList.querySelectorAll('.recommendation-item span');
        recItems.forEach(item => {
            recommendations.push(item.textContent);
        });
        return recommendations;
    }
    
    generateTextReport() {
        // Fallback text report generation (original functionality)
        const diseaseName = this.diseaseName.textContent;
        const confidence = this.confidenceValue.textContent;
        const description = this.diseaseDescription.textContent;
        const timestamp = this.timestamp.textContent;
        
        let report = `POTATO DISEASE DETECTION REPORT\n`;
        report += `=====================================\n\n`;
        report += `${timestamp}\n\n`;
        report += `DIAGNOSIS: ${diseaseName}\n`;
        report += `CONFIDENCE: ${confidence}\n\n`;
        report += `DESCRIPTION:\n${description}\n\n`;
        report += `RECOMMENDATIONS:\n`;
        
        const recommendations = this.recommendationList.querySelectorAll('.recommendation-item span');
        recommendations.forEach((rec, index) => {
            report += `${index + 1}. ${rec.textContent}\n`;
        });
        
        report += `\n=====================================\n`;
        report += `Generated by Potato Disease Detection System\n`;
        report += `Powered by Flask & TensorFlow\n`;
        
        // Download as text file
        const blob = new Blob([report], { type: 'text/plain' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `potato_disease_report_${Date.now()}.txt`;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
    }

    showSuccessMessage(message) {
        this.showMessage(message, 'success');
    }

    showInfoMessage(message) {
        this.showMessage(message, 'info');
    }

    showWarningMessage(message) {
        this.showMessage(message, 'warning');
    }

    showErrorMessage(message) {
        this.showMessage(message, 'error');
    }

    showMessage(message, type = 'info') {
        // Create or update message container
        let messageContainer = document.getElementById('message-container');
        if (!messageContainer) {
            messageContainer = document.createElement('div');
            messageContainer.id = 'message-container';
            messageContainer.style.position = 'fixed';
            messageContainer.style.top = '20px';
            messageContainer.style.right = '20px';
            messageContainer.style.zIndex = '10000';
            messageContainer.style.maxWidth = '400px';
            document.body.appendChild(messageContainer);
        }

        // Create message element
        const messageEl = document.createElement('div');
        messageEl.className = `message message-${type}`;
        messageEl.innerHTML = `
            <div style="
                background: ${this.getMessageColor(type)};
                color: white;
                padding: 12px 16px;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                margin-bottom: 10px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                font-size: 14px;
                animation: slideInRight 0.3s ease-out;
            ">
                <span>${message}</span>
                <button onclick="this.parentElement.parentElement.remove()" 
                        style="background: none; border: none; color: white; font-size: 18px; cursor: pointer; padding: 0; margin-left: 10px;">Γ—</button>
            </div>
        `;

        // Add CSS animation if not already added
        if (!document.getElementById('message-styles')) {
            const style = document.createElement('style');
            style.id = 'message-styles';
            style.textContent = `
                @keyframes slideInRight {
                    from { transform: translateX(100%); opacity: 0; }
                    to { transform: translateX(0); opacity: 1; }
                }
            `;
            document.head.appendChild(style);
        }

        messageContainer.appendChild(messageEl);

        // Auto-remove after 5 seconds
        setTimeout(() => {
            if (messageEl.parentElement) {
                messageEl.remove();
            }
        }, 5000);
    }

    getMessageColor(type) {
        const colors = {
            success: '#10b981', // green
            info: '#3b82f6',    // blue
            warning: '#f59e0b', // amber
            error: '#ef4444'    // red
        };
        return colors[type] || colors.info;
    }
}

// Initialize the application when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    new PotatoDiseaseDetector();
});

// Add some utility functions
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// Mobile device detection and utilities
function isMobileDevice() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

function isIOSDevice() {
    return /iPad|iPhone|iPod/.test(navigator.userAgent);
}

function getOptimalImageSize() {
    const isMobile = isMobileDevice();
    if (isMobile) {
        return {
            maxWidth: window.innerWidth - 40,
            maxHeight: Math.min(window.innerHeight * 0.4, 300)
        };
    }
    return {
        maxWidth: 400,
        maxHeight: 400
    };
}

// Prevent double-tap zoom on mobile
function preventDoubleTab() {
    let lastTouchEnd = 0;
    document.addEventListener('touchend', function (event) {
        const now = (new Date()).getTime();
        if (now - lastTouchEnd <= 300) {
            event.preventDefault();
        }
        lastTouchEnd = now;
    }, false);
}

// Initialize mobile optimizations
if (isMobileDevice()) {
    preventDoubleTab();
    
    // Add mobile class to body for CSS targeting
    document.body.classList.add('mobile-device');
    
    if (isIOSDevice()) {
        document.body.classList.add('ios-device');
    }
    
    // Adjust viewport height for mobile browsers
    function setVH() {
        let vh = window.innerHeight * 0.01;
        document.documentElement.style.setProperty('--vh', `${vh}px`);
    }
    
    setVH();
    window.addEventListener('resize', setVH);
    window.addEventListener('orientationchange', () => {
        setTimeout(setVH, 100);
    });
}

// Check browser compatibility
function checkBrowserSupport() {
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        console.warn('Camera functionality not supported in this browser');
        const cameraCard = document.getElementById('cameraCard');
        if (cameraCard) {
            cameraCard.style.opacity = '0.5';
            cameraCard.style.cursor = 'not-allowed';
            
            // Add tooltip for unsupported browsers
            const tooltip = document.createElement('div');
            tooltip.className = 'tooltip';
            tooltip.textContent = 'Camera not supported in this browser';
            cameraCard.appendChild(tooltip);
        }
    }
    
    // Check for file upload support
    if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
        console.warn('File upload not supported in this browser');
        const uploadCard = document.getElementById('uploadCard');
        if (uploadCard) {
            uploadCard.style.opacity = '0.7';
        }
    }
}

// Run compatibility check
checkBrowserSupport();