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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
console.log('script.js loaded');

let ws = null;

// Initialize WebSocket connection
function connectWebSocket() {
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    ws = new WebSocket(`${protocol}//${window.location.host}/ws`);

    ws.onopen = function () {
        console.log('WebSocket connected');
    };

    ws.onmessage = function (event) {
        const status = JSON.parse(event.data);
        updateIndexingStatus(status);
    };

    ws.onclose = function () {
        console.log('WebSocket disconnected, attempting to reconnect...');
        setTimeout(connectWebSocket, 1000);
    };

    ws.onerror = function (error) {
        console.error('WebSocket error:', error);
    };
}

// Update indexing progress
function updateIndexingStatus(status) {
    const statusDiv = document.getElementById('indexingStatus');
    const progressBar = statusDiv.querySelector('.progress-bar');
    const details = document.getElementById('indexingDetails');

    if (status.status === 'idle') {
        // Fade out the status div
        statusDiv.style.opacity = '0';
        setTimeout(() => {
            statusDiv.style.display = 'none';
            statusDiv.style.opacity = '1';
        }, 500);
        return;
    }

    // Show and update the status
    statusDiv.style.display = 'block';
    statusDiv.style.opacity = '1';

    // Calculate progress percentage
    const percentage = status.total_files > 0
        ? Math.round((status.processed_files / status.total_files) * 100)
        : 0;

    progressBar.style.width = `${percentage}%`;
    progressBar.setAttribute('aria-valuenow', percentage);

    // Update status text
    let statusText = `Status: ${status.status}`;
    if (status.current_file) {
        statusText += ` | Current file: ${status.current_file}`;
    }
    if (status.total_files > 0) {
        statusText += ` | Progress: ${status.processed_files}/${status.total_files} (${percentage}%)`;
    }
    details.textContent = statusText;
}

// IntersectionObserver for lazy loading images
let imageObserver = null;

function observeLazyLoadImages() {
    const lazyLoadImages = document.querySelectorAll('img.lazy-load');

    if (imageObserver) {
        // Disconnect previous observer if any
        imageObserver.disconnect();
    }

    imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                const fullSrc = img.dataset.src;

                if (fullSrc) {
                    img.src = fullSrc;
                    img.removeAttribute('data-src');
                    img.classList.remove('lazy-load');
                }
                observer.unobserve(img);
            }
        });
    }, {
        rootMargin: '0px 0px 200px 0px'
    });

    lazyLoadImages.forEach(img => {
        imageObserver.observe(img);
    });
}

// Open file upload dialog
function openFileUpload() {
    document.getElementById('multipleImageUpload').click();
}

// Upload images
async function uploadImages(event) {
    const files = event.target.files;
    if (!files || files.length === 0) return;

    // Validate file types
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    const validFiles = Array.from(files).filter(file => 
        allowedTypes.includes(file.type.toLowerCase())
    );

    if (validFiles.length === 0) {
        alert('Please select valid image files (JPEG, PNG, GIF, WebP)');
        return;
    }

    if (validFiles.length !== files.length) {
        const skipped = files.length - validFiles.length;
        alert(`${skipped} file(s) were skipped as they are not valid image files`);
    }

    try {
        // Show upload progress
        showUploadProgress(validFiles.length);

        const formData = new FormData();
        validFiles.forEach(file => {
            formData.append('files', file);
        });

        const response = await fetch('/upload', {
            method: 'POST',
            body: formData
        });

        if (response.ok) {
            const result = await response.json();
            hideUploadProgress();
            
            // Show success message
            showNotification('success', `Successfully uploaded ${validFiles.length} image(s)!`);
            
            // Reload folders and images
            await loadIndexedFolders();
        } else {
            const error = await response.json();
            hideUploadProgress();
            showNotification('error', `Upload failed: ${error.detail || 'Unknown error'}`);
        }
    } catch (error) {
        console.error('Upload error:', error);
        hideUploadProgress();
        showNotification('error', 'Upload failed. Please try again.');
    }

    // Reset file input
    event.target.value = '';
}

// Show upload progress
function showUploadProgress(fileCount) {
    const progressDiv = document.getElementById('uploadProgress');
    const statusText = document.getElementById('uploadStatus');
    
    progressDiv.style.display = 'block';
    statusText.textContent = `Uploading ${fileCount} image(s)...`;
    
    // Simulate progress
    const progressBar = document.getElementById('uploadProgressBar');
    let progress = 0;
    
    const interval = setInterval(() => {
        progress += 5;
        progressBar.style.width = `${progress}%`;
        
        if (progress >= 90) {
            statusText.textContent = 'Processing and indexing images...';
            clearInterval(interval);
        }
    }, 100);
    
    progressDiv.dataset.intervalId = interval;
}

// Hide upload progress
function hideUploadProgress() {
    const progressDiv = document.getElementById('uploadProgress');
    const progressBar = document.getElementById('uploadProgressBar');
    
    if (progressDiv.dataset.intervalId) {
        clearInterval(progressDiv.dataset.intervalId);
        delete progressDiv.dataset.intervalId;
    }
    
    progressBar.style.width = '100%';
    
    setTimeout(() => {
        progressDiv.style.display = 'none';
        progressBar.style.width = '0%';
    }, 1000);
}

// Show notification
function showNotification(type, message) {
    const notification = document.createElement('div');
    notification.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show position-fixed`;
    notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; max-width: 400px;';
    
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        if (notification.parentNode) {
            notification.remove();
        }
    }, 5000);
}

// Load indexed folders
async function loadIndexedFolders() {
    try {
        const response = await fetch('/folders');
        const folders = await response.json();

        const folderList = document.getElementById('folderList');
        folderList.innerHTML = '';

        if (folders.length === 0) {
            folderList.innerHTML = `
                <div class="text-center p-4 text-muted">
                    <i class="bi bi-folder-x fs-2 d-block mb-2"></i>
                    <small>No folders indexed yet</small>
                </div>
            `;
            return;
        }

        folders.forEach(folder => {
            const escapedPath = folder.path.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
            const folderCard = document.createElement('div');
            folderCard.className = `folder-item-card ${!folder.is_valid ? 'invalid' : ''}`;
            folderCard.innerHTML = `
                <div class="d-flex justify-content-between align-items-start p-3">
                    <div class="flex-grow-1 me-2">
                        <div class="d-flex align-items-center mb-1">
                            <i class="bi bi-folder-fill me-2 ${folder.is_valid ? 'text-primary' : 'text-danger'}"></i>
                            <span class="fw-semibold ${!folder.is_valid ? 'text-danger' : 'text-dark'}" style="font-size: 0.9rem;">
                                ${folder.path.split(/[\\/]/).pop()}
                            </span>
                        </div>
                        <div class="text-muted small" style="word-break: break-all; line-height: 1.3;">
                            ${folder.path}
                        </div>
                        ${!folder.is_valid ? '<small class="text-danger"><i class="bi bi-exclamation-triangle me-1"></i>Path not accessible</small>' : ''}
                    </div>
                    <button class="btn btn-outline-danger btn-sm" onclick="removeFolder('${escapedPath}')" title="Remove folder">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            `;
            folderList.appendChild(folderCard);
        });

        // Load images from all folders
        await loadImages();
    } catch (error) {
        console.error('Error loading folders:', error);
    }
}

// Remove folder
async function removeFolder(path) {
    if (confirm('Are you sure you want to remove this folder?')) {
        try {
            const encodedPath = encodeURIComponent(path).replace(/%5C/g, '\\');
            const response = await fetch(`/folders/${encodedPath}`, {
                method: 'DELETE'
            });

            if (response.ok) {
                await loadIndexedFolders();
            } else {
                const error = await response.text();
                alert(`Error removing folder: ${error}`);
            }
        } catch (error) {
            console.error('Error removing folder:', error);
            alert('Error removing folder. Please try again.');
        }
    }
}

// Load images
async function loadImages(folder = null) {
    try {
        const url = folder ? `/images?folder=${encodeURIComponent(folder)}` : '/images';
        const response = await fetch(url);
        const images = await response.json();

        const imageGrid = document.getElementById('imageGrid');
        imageGrid.innerHTML = '';

        if (images.length === 0) {
            imageGrid.innerHTML = `
                <div class="col-12">
                    <div class="text-center p-5">
                        <i class="bi bi-images fs-1 text-muted d-block mb-3"></i>
                        <h5 class="text-muted mb-2">No images found</h5>
                        <p class="text-muted">Upload some images to start building your visual search database</p>
                    </div>
                </div>
            `;
            return;
        }

        images.forEach(image => {
            const card = document.createElement('div');
            card.className = 'image-card';
            card.innerHTML = `
                <div class="image-wrapper">
                    <img class="lazy-load"
                         src="/thumbnail/${image.id}"
                         data-src="/image/${image.id}"
                         alt="${image.filename || image.path}"
                         loading="lazy">
                </div>
                <div class="image-info">
                    <span class="filename" title="${image.filename || image.path}">${image.filename || image.path}</span>
                    <span class="file-size">${formatFileSize(image.file_size)}</span>
                </div>
            `;
            imageGrid.appendChild(card);
        });
        observeLazyLoadImages();
    } catch (error) {
        console.error('Error loading images:', error);
        const imageGrid = document.getElementById('imageGrid');
        imageGrid.innerHTML = '<div class="col-12"><div class="error text-center p-4">Error loading images. Please try again.</div></div>';
    }
}

// Utility function to format file sizes
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];
}

// Search images
async function searchImages(event) {
    event.preventDefault();
    const query = document.getElementById('searchInput').value;
    if (!query) return;

    try {
        const searchUrl = `/search/text?query=${encodeURIComponent(query)}`;
        const response = await fetch(searchUrl);
        const results = await response.json();

        displaySearchResults(results);
    } catch (error) {
        console.error('Error searching images:', error);
        const imageGrid = document.getElementById('imageGrid');
        imageGrid.innerHTML = `
            <div class="col-12">
                <div class="error text-center p-5">
                    <i class="bi bi-exclamation-triangle fs-1 text-danger d-block mb-3"></i>
                    <h5 class="text-danger mb-2">Search Error</h5>
                    <p class="text-muted">An error occurred while searching. Please try again.</p>
                </div>
            </div>
        `;
    }
}

// Search by image
async function searchByImage(event) {
    const file = event.target.files[0];
    if (!file) return;

    const formData = new FormData();
    formData.append('file', file);

    try {
        const searchUrl = '/search/image';
        const response = await fetch(searchUrl, {
            method: 'POST',
            body: formData
        });
        const results = await response.json();

        displaySearchResults(results);
        event.target.value = '';
    } catch (error) {
        console.error('Error searching by image:', error);
        const imageGrid = document.getElementById('imageGrid');
        imageGrid.innerHTML = `
            <div class="col-12">
                <div class="error text-center p-5">
                    <i class="bi bi-exclamation-triangle fs-1 text-danger d-block mb-3"></i>
                    <h5 class="text-danger mb-2">Image Search Error</h5>
                    <p class="text-muted">An error occurred while processing your image. Please try again.</p>
                </div>
            </div>
        `;
    }
}

// Search by URL
async function searchByUrl(event) {
    event.preventDefault();
    const url = document.getElementById('urlInput').value;
    if (!url) return;

    try {
        const imageGrid = document.getElementById('imageGrid');
        imageGrid.innerHTML = `
            <div class="col-12">
                <div class="loading text-center p-5">
                    <div class="spinner-border text-primary mb-3" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <h5 class="text-primary mb-2">Downloading and analyzing image...</h5>
                    <p class="text-muted">This may take a few moments</p>
                </div>
            </div>
        `;

        const searchUrl = `/search/url?url=${encodeURIComponent(url)}`;
        const response = await fetch(searchUrl);
        const results = await response.json();

        displaySearchResults(results);
        document.getElementById('urlInput').value = '';
        toggleUrlSearch();
    } catch (error) {
        console.error('Error searching by URL:', error);
        const imageGrid = document.getElementById('imageGrid');
        imageGrid.innerHTML = `
            <div class="col-12">
                <div class="error text-center p-5">
                    <i class="bi bi-exclamation-triangle fs-1 text-danger d-block mb-3"></i>
                    <h5 class="text-danger mb-2">Error processing URL</h5>
                    <p class="text-muted">Please check the URL and try again. Make sure it points to a valid image.</p>
                </div>
            </div>
        `;
    }
}

// Display search results
function displaySearchResults(results) {
    const imageGrid = document.getElementById('imageGrid');
    imageGrid.innerHTML = '';

    if (results.length === 0) {
        imageGrid.innerHTML = `
            <div class="col-12">
                <div class="no-results text-center p-5">
                    <i class="bi bi-search fs-1 text-muted d-block mb-3"></i>
                    <h5 class="text-muted mb-2">No similar images found</h5>
                    <p class="text-muted">Try adjusting your search terms or uploading a different image</p>
                </div>
            </div>
        `;
        return;
    }

    results.forEach(result => {
        const card = document.createElement('div');
        card.className = 'image-card';
        card.innerHTML = `
            <div class="image-wrapper">
                <img class="lazy-load"
                     src="/thumbnail/${result.id}"
                     data-src="/image/${result.id}"
                     alt="${result.filename || result.path}"
                     loading="lazy">
                <div class="similarity-score">${result.similarity}%</div>
            </div>
            <div class="image-info">
                <span class="filename" title="${result.filename || result.path}">${result.filename || result.path}</span>
                <span class="file-size">${formatFileSize(result.file_size)}</span>
            </div>
        `;
        imageGrid.appendChild(card);
    });
    observeLazyLoadImages();
}

// Toggle URL search form visibility
function toggleUrlSearch() {
    const urlForm = document.getElementById('urlSearchForm');
    const isVisible = urlForm.style.display !== 'none';
    
    if (isVisible) {
        urlForm.style.display = 'none';
        document.getElementById('urlInput').value = '';
    } else {
        urlForm.style.display = 'flex';
        document.getElementById('urlInput').focus();
    }
}

// Initialize
document.addEventListener('DOMContentLoaded', () => {
    connectWebSocket();
    loadIndexedFolders();
});

// Initialize folder browser
async function initFolderBrowser() {
    folderModal = new bootstrap.Modal(document.getElementById('folderBrowserModal'));
    await loadFolderContents();
    await loadIndexedFolders();
}

// Open folder browser modal
function openFolderBrowser() {
    selectedFolder = null;
    folderModal.show();
    loadFolderContents();
}

function showDrives(breadcrumb, browser, data) {
    // Windows drives
    breadcrumb.innerHTML = '<li class="breadcrumb-item active">Drives</li>';
    data.drives.forEach(drive => {
        const escapedDrive = drive.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
        browser.innerHTML += `
                    <div class="folder-item" onclick="loadFolderContents('${escapedDrive}')">
                        <i class="bi bi-hdd"></i>${drive}
                    </div>
                `;
    });
}

function showFolderContents(breadcrumb, browser, data) {
    // Folder contents
    currentPath = data.current_path;

    // Update breadcrumb
    const pathParts = currentPath.split(/[\\/]/);
    let currentBreadcrumb = '';
    pathParts.forEach((part, index) => {
        if (part) {
            // Check if the path contains backslashes to detect Windows
            const isWindows = currentPath.includes('\\');
            currentBreadcrumb += part + (isWindows ? '\\' : '/');
            const isLast = index === pathParts.length - 1;
            const escapedPath = currentBreadcrumb.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
            breadcrumb.innerHTML += `
                                    <li class="breadcrumb-item ${isLast ? 'active' : ''}">
                                        ${isLast ? part : `<a href="#" onclick="loadFolderContents('${escapedPath}')">${part}</a>`}
                                    </li>
                                `;
        }
    });

    // Add parent directory
    if (data.parent_path) {
        addParentDirectory(browser, data);
    }

    // Add folders and files
    addFolderContents(browser, data);
}

function addParentDirectory(browser, data) {
    const escapedParentPath = data.parent_path.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
    browser.innerHTML += `
                            <div class="folder-item" onclick="loadFolderContents('${escapedParentPath}')">
                                <i class="bi bi-arrow-up"></i>..
                            </div>
                        `;
}

function addFolderContents(browser, data) {
    data.contents.forEach(item => {
        const icon = item.type === 'directory' ? 'bi-folder' : 'bi-image';
        const escapedPath = item.path.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
        browser.innerHTML += `
                                <div class="folder-item" onclick="${item.type === 'directory' ? `loadFolderContents('${escapedPath}')` : ''}" ondblclick="${item.type === 'directory' ? `selectFolder('${escapedPath}')` : ''}">
                                    <i class="bi ${icon}"></i>${item.name}
                                </div>
                            `;
    });
}

// Load folder contents
async function loadFolderContents(path = null) {
    try {
        const url = path ? `/browse/${encodeURIComponent(path)}` : '/browse';
        const response = await fetch(url);
        const data = await response.json();

        const browser = document.getElementById('folderBrowser');
        const breadcrumb = document.getElementById('folderBreadcrumb');

        browser.innerHTML = '';
        breadcrumb.innerHTML = '';

        if (data.drives) {
            showDrives(breadcrumb, browser, data);
        } else {
            showFolderContents(breadcrumb, browser, data);
        }
    } catch (error) {
        console.error('Error loading folder contents:', error);
    }
}

// Select folder for indexing
function selectFolder(path) {
    selectedFolder = path;
    addSelectedFolder();
}

// Add selected folder
async function addSelectedFolder() {

    folderModal.hide();

    if (!selectedFolder && currentPath) {
        selectedFolder = currentPath;
    }

    if (selectedFolder) {
        try {
            const encodedPath = encodeURIComponent(selectedFolder);
            const response = await fetch(`/folders?folder_path=${encodedPath}`, {
                method: 'POST'
            });

            if (response.ok) {
                await loadIndexedFolders();
                selectedFolder = null;
            } else {
                const error = await response.json();
                alert(`Error adding folder: ${error.detail || error.message || JSON.stringify(error)}`);
            }
        } catch (error) {
            console.error('Error adding folder:', error);
            alert('Error adding folder. Please try again.');
        }
    }
}

// Load indexed folders
async function loadIndexedFolders() {
    try {
        const response = await fetch('/folders');
        const folders = await response.json();

        const folderList = document.getElementById('folderList');
        folderList.innerHTML = '';

        if (folders.length === 0) {
            folderList.innerHTML = `
                <div class="text-center p-4 text-muted">
                    <i class="bi bi-folder-x fs-2 d-block mb-2"></i>
                    <small>No folders indexed yet</small>
                </div>
            `;
            return;
        }

        folders.forEach(folder => {
            const escapedPath = folder.path.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
            const folderCard = document.createElement('div');
            folderCard.className = `folder-item-card ${!folder.is_valid ? 'invalid' : ''}`;
            folderCard.innerHTML = `
                <div class="d-flex justify-content-between align-items-start p-3">
                    <div class="flex-grow-1 me-2">
                        <div class="d-flex align-items-center mb-1">
                            <i class="bi bi-folder-fill me-2 ${folder.is_valid ? 'text-primary' : 'text-danger'}"></i>
                            <span class="fw-semibold ${!folder.is_valid ? 'text-danger' : 'text-dark'}" style="font-size: 0.9rem;">
                                ${folder.path.split(/[\\/]/).pop()}
                            </span>
                        </div>
                        <div class="text-muted small" style="word-break: break-all; line-height: 1.3;">
                            ${folder.path}
                        </div>
                        ${!folder.is_valid ? '<small class="text-danger"><i class="bi bi-exclamation-triangle me-1"></i>Path not accessible</small>' : ''}
                    </div>
                    <button class="btn btn-outline-danger btn-sm" onclick="removeFolder('${escapedPath}')" title="Remove folder">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            `;
            folderList.appendChild(folderCard);
        });

        // Load images from all folders
        await loadImages();
    } catch (error) {
        console.error('Error loading folders:', error);
    }
}

// Remove folder
async function removeFolder(path) {
    if (confirm('Are you sure you want to remove this folder?')) {
        try {
            const encodedPath = encodeURIComponent(path).replace(/%5C/g, '\\');
            const response = await fetch(`/folders/${encodedPath}`, {
                method: 'DELETE'
            });

            if (response.ok) {
                await loadIndexedFolders();
            } else {
                const error = await response.text();
                alert(`Error removing folder: ${error}`);
            }
        } catch (error) {
            console.error('Error removing folder:', error);
            alert('Error removing folder. Please try again.');
        }
    }
}

// Load images
async function loadImages(folder = null) {
    try {
        const url = folder ? `/images?folder=${encodeURIComponent(folder)}` : '/images';
        const response = await fetch(url);
        const images = await response.json();

        const imageGrid = document.getElementById('imageGrid');
        imageGrid.innerHTML = '';

        if (images.length === 0) {
            imageGrid.innerHTML = `
                <div class="col-12">
                    <div class="text-center p-5">
                        <i class="bi bi-images fs-1 text-muted d-block mb-3"></i>
                        <h5 class="text-muted mb-2">No images found</h5>
                        <p class="text-muted">Add some folders to start indexing your images</p>
                    </div>
                </div>
            `;
            return;
        }

        images.forEach(image => {
            const card = document.createElement('div');
            card.className = 'image-card';
            card.innerHTML = `
                <div class="image-wrapper">
                    <img class="lazy-load"
                         src="/thumbnail/${image.id}"
                         data-src="/image/${image.id}"
                         alt="${image.filename || image.path}"
                         loading="lazy">
                </div>
                <div class="image-info">
                    <span class="filename" title="${image.filename || image.path}">${image.filename || image.path}</span>
                    <span class="file-size">${formatFileSize(image.file_size)}</span>
                </div>
            `;
            imageGrid.appendChild(card);
        });
        observeLazyLoadImages(); // Initialize IntersectionObserver for new images
    } catch (error) {
        console.error('Error loading images:', error);
        const imageGrid = document.getElementById('imageGrid');
        imageGrid.innerHTML = '<div class="col-12"><div class="error text-center p-4">Error loading images. Please try again.</div></div>';
    }
}

// Utility function to format file sizes
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];
}

// Get current folder path
function getCurrentPath() {
    // Return the current path if we're in a folder, otherwise null
    return currentPath;
}

// Search images
async function searchImages(event) {
    event.preventDefault();
    const query = document.getElementById('searchInput').value;
    if (!query) return;

    try {
        // Only include folder parameter if we're inside the folder browser
        const searchUrl = `/search/text?query=${encodeURIComponent(query)}`;
        const response = await fetch(searchUrl);
        const results = await response.json();

        displaySearchResults(results);
    } catch (error) {
        console.error('Error searching images:', error);
        const imageGrid = document.getElementById('imageGrid');
        imageGrid.innerHTML = `
            <div class="col-12">
                <div class="error text-center p-5">
                    <i class="bi bi-exclamation-triangle fs-1 text-danger d-block mb-3"></i>
                    <h5 class="text-danger mb-2">Search Error</h5>
                    <p class="text-muted">An error occurred while searching. Please try again.</p>
                </div>
            </div>
        `;
    }
}

// Search by image
async function searchByImage(event) {
    const file = event.target.files[0];
    if (!file) return;

    const formData = new FormData();
    formData.append('file', file);

    try {
        const searchUrl = '/search/image';
        const response = await fetch(searchUrl, {
            method: 'POST',
            body: formData
        });
        const results = await response.json();

        displaySearchResults(results);

        // Reset file input
        event.target.value = '';
    } catch (error) {
        console.error('Error searching by image:', error);
        const imageGrid = document.getElementById('imageGrid');
        imageGrid.innerHTML = `
            <div class="col-12">
                <div class="error text-center p-5">
                    <i class="bi bi-exclamation-triangle fs-1 text-danger d-block mb-3"></i>
                    <h5 class="text-danger mb-2">Image Search Error</h5>
                    <p class="text-muted">An error occurred while processing your image. Please try again.</p>
                </div>
            </div>
        `;
    }
}

// Search by URL
async function searchByUrl(event) {
    event.preventDefault();
    const url = document.getElementById('urlInput').value;
    if (!url) return;

    try {
        // Show loading state
        const imageGrid = document.getElementById('imageGrid');
        imageGrid.innerHTML = `
            <div class="col-12">
                <div class="loading text-center p-5">
                    <div class="spinner-border text-primary mb-3" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <h5 class="text-primary mb-2">Downloading and analyzing image...</h5>
                    <p class="text-muted">This may take a few moments</p>
                </div>
            </div>
        `;

        const searchUrl = `/search/url?url=${encodeURIComponent(url)}`;
        const response = await fetch(searchUrl);
        const results = await response.json();

        displaySearchResults(results);

        // Clear URL input and hide form
        document.getElementById('urlInput').value = '';
        toggleUrlSearch();
    } catch (error) {
        console.error('Error searching by URL:', error);
        const imageGrid = document.getElementById('imageGrid');
        imageGrid.innerHTML = `
            <div class="col-12">
                <div class="error text-center p-5">
                    <i class="bi bi-exclamation-triangle fs-1 text-danger d-block mb-3"></i>
                    <h5 class="text-danger mb-2">Error processing URL</h5>
                    <p class="text-muted">Please check the URL and try again. Make sure it points to a valid image.</p>
                </div>
            </div>
        `;
    }
}

// Display search results (common function for all search types)
function displaySearchResults(results) {
    const imageGrid = document.getElementById('imageGrid');
    imageGrid.innerHTML = '';

    if (results.length === 0) {
        imageGrid.innerHTML = `
            <div class="col-12">
                <div class="no-results text-center p-5">
                    <i class="bi bi-search fs-1 text-muted d-block mb-3"></i>
                    <h5 class="text-muted mb-2">No similar images found</h5>
                    <p class="text-muted">Try adjusting your search terms or uploading a different image</p>
                </div>
            </div>
        `;
        return;
    }

    results.forEach(result => {
        const card = document.createElement('div');
        card.className = 'image-card';
        card.innerHTML = `
            <div class="image-wrapper">
                <img class="lazy-load"
                     src="/thumbnail/${result.id}"
                     data-src="/image/${result.id}"
                     alt="${result.filename || result.path}"
                     loading="lazy">
                <div class="similarity-score">${result.similarity}%</div>
            </div>
            <div class="image-info">
                <span class="filename" title="${result.filename || result.path}">${result.filename || result.path}</span>
                <span class="file-size">${formatFileSize(result.file_size)}</span>
            </div>
        `;
        imageGrid.appendChild(card);
    });
    observeLazyLoadImages(); // Initialize IntersectionObserver for new images
}

// Toggle URL search form visibility
function toggleUrlSearch() {
    const urlForm = document.getElementById('urlSearchForm');
    const isVisible = urlForm.style.display !== 'none';
    
    if (isVisible) {
        urlForm.style.display = 'none';
        document.getElementById('urlInput').value = '';
    } else {
        urlForm.style.display = 'flex';
        document.getElementById('urlInput').focus();
    }
}

// Initialize
document.addEventListener('DOMContentLoaded', () => {
    connectWebSocket();
    initFolderBrowser();
});