{{-- Media Box Partial - Redesigned with Lazy Loading --}}
<div class="modern-card media-box-card">
    <div class="card-header">
        <h4><i class="uil uil-images"></i> Documents & Médias</h4>
        <span class="doc-count-badge" id="docCountBadge">{{ $dossier->document ? $dossier->document->where('type_document_id', '!=', 10)->count() : 0 }}</span>
    </div>
    <div class="card-body">
        <!-- Filter Tabs -->
        <div class="media-filter-tabs">
            <button type="button" data-filter="ALL" class="filter-tab active" value="ALL">
                <i class="uil uil-apps"></i> Tout
            </button>
            @foreach ($typedocuments as $type)
                <button type="button" data-filter="{{ $type->type }}" class="filter-tab" value="{{ $type->id }}">
                    {{ $type->type }}
                </button>
            @endforeach
        </div>

        <!-- Media Gallery -->
        <div class="media-gallery" id="mediaGallery">
            <input type="hidden" id="dossierId" name="dossier_id" value="{{ $dossier->id }}">
            
            @if ($dossier->document && $dossier->document->count() > 0)
                <div class="media-grid" id="mediaGrid">
                    @foreach ($dossier->document as $doc)
                        @if ($doc->type_document_id != 10)
                            <div class="media-item {{ $doc->typedocument->type ?? '' }}" 
                                 data-doc-id="{{ $doc->id }}"
                                 data-doc-path="{{ $doc->path }}"
                                 data-doc-type="{{ $doc->typedocument->type ?? 'Document' }}">
                                
                                <!-- Placeholder - No S3 fetch until clicked -->
                                <div class="media-placeholder" onclick="loadAndViewImage(this, {{ $doc->id }})">
                                    <div class="placeholder-content">
                                        <i class="uil uil-image"></i>
                                        <span>Cliquer pour voir</span>
                                    </div>
                                    <div class="loading-spinner" style="display: none;">
                                        <div class="spinner"></div>
                                        <span>Chargement...</span>
                                    </div>
                                </div>

                                <!-- Actions Overlay -->
                                <div class="media-actions">
                                    <button type="button" class="media-action-btn view-btn" onclick="loadAndViewImage(this.closest('.media-item'), {{ $doc->id }})" title="Voir">
                                        <i class="uil uil-eye"></i>
                                    </button>
                                    <a href="{{ route('Document.edit', $doc->id) }}" class="media-action-btn edit-btn" title="Modifier">
                                        <i class="uil uil-edit"></i>
                                    </a>
                                    <button type="button" class="media-action-btn download-btn" onclick="downloadDocument({{ $doc->id }})" title="Télécharger">
                                        <i class="uil uil-download-alt"></i>
                                    </button>
                                    @if (Auth::user()->role_id == 4 && $doc->type_document_id != 4 && $doc->type_document_id != 8)
                                        <form class="deleteForm" action="{{ route('Document.destroy', $doc->id) }}" method="post" style="display: inline;">
                                            @csrf
                                            @method('DELETE')
                                            <button type="button" class="media-action-btn delete-btn confirmDelete" title="Supprimer">
                                                <i class="uil uil-trash-alt"></i>
                                            </button>
                                        </form>
                                    @endif
                                </div>

                                <!-- Document Badge -->
                                <div class="media-badge {{ $doc->rejected ? 'rejected' : ($doc->signer ? 'signed' : 'normal') }}">
                                    {{ $doc->typedocument->type ?? 'Document' }}
                                    @if ($doc->type_document_id == 8)
                                        - {{ $doc->facture_mo ? 'MO' : 'Pièce' }}
                                    @endif
                                    @if (($doc->typedocument->id ?? 0) == 4 || ($doc->typedocument->id ?? 0) == 29)
                                        {{ $doc->devis[0]->devis ?? '' }}
                                    @endif
                                </div>

                                <!-- Status Indicator -->
                                @if ($doc->rejected)
                                    <div class="status-indicator rejected" title="Rejeté">
                                        <i class="uil uil-times-circle"></i>
                                    </div>
                                @elseif ($doc->signer)
                                    <div class="status-indicator signed" title="Signé">
                                        <i class="uil uil-check-circle"></i>
                                    </div>
                                @endif
                            </div>
                        @endif
                    @endforeach
                </div>
            @else
                <div class="no-media">
                    <i class="uil uil-folder-open"></i>
                    <p>Aucun document disponible</p>
                </div>
            @endif
        </div>
    </div>
</div>

<!-- Image Viewer Modal - Full Document View -->
<div class="image-viewer-modal" id="imageViewerModal">
    <div class="viewer-backdrop" onclick="closeImageViewer()"></div>
    <div class="viewer-container">
        <div class="viewer-header">
            <span class="viewer-title" id="viewerTitle">Document</span>
            <div class="viewer-controls">
                <button onclick="resetView()" title="Réinitialiser"><i class="uil uil-redo"></i></button>
                <button onclick="zoomOut()" title="Zoom -"><i class="uil uil-search-minus"></i></button>
                <span class="zoom-level" id="zoomLevel">100%</span>
                <button onclick="zoomIn()" title="Zoom +"><i class="uil uil-search-plus"></i></button>
                <button onclick="rotateImage()" title="Pivoter"><i class="uil uil-corner-up-right"></i></button>
                <button onclick="downloadCurrentImage()" title="Télécharger"><i class="uil uil-download-alt"></i></button>
                <button onclick="closeImageViewer()" title="Fermer" class="close-btn"><i class="uil uil-times"></i></button>
            </div>
        </div>
        <div class="viewer-body" id="viewerBody">
            <div class="viewer-scroll-container" id="viewerScrollContainer">
                <img id="viewerImage" src="" alt="Document">
            </div>
            <div class="viewer-loading" id="viewerLoading">
                <div class="spinner-large"></div>
                <p>Chargement du document...</p>
            </div>
        </div>
        <div class="viewer-nav">
            <button class="nav-btn prev" onclick="viewPrevImage()"><i class="uil uil-angle-left"></i></button>
            <span class="nav-counter" id="navCounter">1 / 1</span>
            <button class="nav-btn next" onclick="viewNextImage()"><i class="uil uil-angle-right"></i></button>
        </div>
    </div>
</div>

<style>
/* ============================================
   MEDIA BOX - MODERN REDESIGN
   ============================================ */

.media-box-card .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.doc-count-badge {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: #fff;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

/* Filter Tabs */
.media-filter-tabs {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e2e8f0;
}

.filter-tab {
    padding: 8px 16px;
    border: 1px solid #e2e8f0;
    background: #fff;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
    color: #64748b;
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    gap: 6px;
}

.filter-tab:hover {
    border-color: #10b981;
    color: #10b981;
}

.filter-tab.active {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    border-color: #10b981;
    color: #fff;
}

.filter-tab i {
    font-size: 14px;
}

/* Media Gallery */
.media-gallery {
    max-height: 500px;
    overflow-y: auto;
    padding-right: 5px;
}

.media-gallery::-webkit-scrollbar {
    width: 6px;
}

.media-gallery::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 3px;
}

.media-gallery::-webkit-scrollbar-thumb {
    background: #cbd5e1;
    border-radius: 3px;
}

.media-gallery::-webkit-scrollbar-thumb:hover {
    background: #94a3b8;
}

/* Media Grid */
.media-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    gap: 15px;
}

/* Media Item */
.media-item {
    position: relative;
    border-radius: 12px;
    overflow: hidden;
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    aspect-ratio: 1;
    transition: all 0.3s ease;
}

.media-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
    border-color: #10b981;
}

/* Placeholder - Shown before S3 image loads */
.media-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    transition: all 0.2s ease;
}

.media-placeholder:hover {
    background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
}

.placeholder-content {
    text-align: center;
    color: #64748b;
}

.placeholder-content i {
    font-size: 36px;
    display: block;
    margin-bottom: 8px;
    color: #94a3b8;
}

.placeholder-content span {
    font-size: 11px;
    font-weight: 500;
}

/* Loading Spinner */
.loading-spinner {
    text-align: center;
    color: #10b981;
}

.loading-spinner .spinner {
    width: 30px;
    height: 30px;
    border: 3px solid #e2e8f0;
    border-top-color: #10b981;
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
    margin: 0 auto 8px;
}

.loading-spinner span {
    font-size: 11px;
    font-weight: 500;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

/* Loaded Image */
.media-item img.media-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    cursor: pointer;
}

/* Actions Overlay */
.media-actions {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    padding: 8px;
    display: flex;
    gap: 5px;
    justify-content: flex-end;
    opacity: 0;
    transition: opacity 0.2s ease;
    background: linear-gradient(180deg, rgba(0,0,0,0.5) 0%, transparent 100%);
}

.media-item:hover .media-actions {
    opacity: 1;
}

.media-action-btn {
    width: 28px;
    height: 28px;
    border-radius: 6px;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 14px;
    text-decoration: none;
}

.media-action-btn.view-btn {
    background: rgba(59, 130, 246, 0.9);
    color: #fff;
}

.media-action-btn.edit-btn {
    background: rgba(245, 158, 11, 0.9);
    color: #fff;
}

.media-action-btn.download-btn {
    background: rgba(16, 185, 129, 0.9);
    color: #fff;
}

.media-action-btn.delete-btn {
    background: rgba(239, 68, 68, 0.9);
    color: #fff;
}

.media-action-btn:hover {
    transform: scale(1.1);
}

/* Media Badge */
.media-badge {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 6px 10px;
    font-size: 10px;
    font-weight: 600;
    text-align: center;
    text-transform: uppercase;
    letter-spacing: 0.3px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.media-badge.normal {
    background: linear-gradient(135deg, rgba(59, 130, 246, 0.95) 0%, rgba(37, 99, 235, 0.95) 100%);
    color: #fff;
}

.media-badge.signed {
    background: linear-gradient(135deg, rgba(16, 185, 129, 0.95) 0%, rgba(5, 150, 105, 0.95) 100%);
    color: #fff;
}

.media-badge.rejected {
    background: linear-gradient(135deg, rgba(239, 68, 68, 0.95) 0%, rgba(220, 38, 38, 0.95) 100%);
    color: #fff;
}

/* Status Indicator */
.status-indicator {
    position: absolute;
    top: 8px;
    left: 8px;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
}

.status-indicator.signed {
    background: #10b981;
    color: #fff;
}

.status-indicator.rejected {
    background: #ef4444;
    color: #fff;
}

/* No Media */
.no-media {
    text-align: center;
    padding: 50px 20px;
    color: #94a3b8;
}

.no-media i {
    font-size: 50px;
    margin-bottom: 15px;
    display: block;
}

.no-media p {
    margin: 0;
    font-size: 14px;
}

/* ============================================
   IMAGE VIEWER MODAL - FULL DOCUMENT VIEW
   ============================================ */

.image-viewer-modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;
}

.image-viewer-modal.open {
    display: flex;
    flex-direction: column;
}

.viewer-backdrop {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.95);
}

.viewer-container {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    z-index: 1;
}

/* Header */
.viewer-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 20px;
    background: rgba(0, 0, 0, 0.8);
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    flex-shrink: 0;
}

.viewer-title {
    color: #fff;
    font-size: 16px;
    font-weight: 600;
}

.viewer-controls {
    display: flex;
    align-items: center;
    gap: 8px;
}

.viewer-controls button {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    border: none;
    background: rgba(255, 255, 255, 0.1);
    color: #fff;
    font-size: 18px;
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    justify-content: center;
}

.viewer-controls button:hover {
    background: rgba(255, 255, 255, 0.2);
}

.viewer-controls button.close-btn {
    background: rgba(239, 68, 68, 0.3);
}

.viewer-controls button.close-btn:hover {
    background: rgba(239, 68, 68, 0.6);
}

.zoom-level {
    color: #10b981;
    font-size: 14px;
    font-weight: 600;
    min-width: 50px;
    text-align: center;
    padding: 0 8px;
}

/* Viewer Body - SCROLLABLE CONTAINER */
.viewer-body {
    flex: 1;
    position: relative;
    overflow: hidden;
    background: #1a1a1a;
}

.viewer-scroll-container {
    width: 100%;
    height: 100%;
    overflow: auto;
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
    padding: 20px;
}

/* Custom Scrollbar for Viewer */
.viewer-scroll-container::-webkit-scrollbar {
    width: 12px;
    height: 12px;
}

.viewer-scroll-container::-webkit-scrollbar-track {
    background: rgba(255, 255, 255, 0.05);
}

.viewer-scroll-container::-webkit-scrollbar-thumb {
    background: rgba(16, 185, 129, 0.5);
    border-radius: 6px;
    border: 2px solid transparent;
    background-clip: padding-box;
}

.viewer-scroll-container::-webkit-scrollbar-thumb:hover {
    background: rgba(16, 185, 129, 0.8);
}

.viewer-scroll-container::-webkit-scrollbar-corner {
    background: rgba(255, 255, 255, 0.05);
}

/* Image - Natural Size, Scalable */
#viewerImage {
    max-width: none;
    max-height: none;
    display: block;
    margin: auto;
    transition: transform 0.1s ease;
    cursor: grab;
    transform-origin: top left;
}

#viewerImage:active {
    cursor: grabbing;
}

#viewerImage.fit-width {
    width: 100%;
    height: auto;
}

#viewerImage.fit-height {
    width: auto;
    height: calc(100vh - 140px);
}

#viewerImage.fit-contain {
    max-width: 100%;
    max-height: calc(100vh - 140px);
    width: auto;
    height: auto;
}

/* Loading State */
.viewer-loading {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #fff;
    background: rgba(0, 0, 0, 0.8);
}

.spinner-large {
    width: 50px;
    height: 50px;
    border: 4px solid rgba(255, 255, 255, 0.2);
    border-top-color: #10b981;
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
    margin-bottom: 15px;
}

/* Navigation */
.viewer-nav {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 20px;
    padding: 12px;
    background: rgba(0, 0, 0, 0.8);
    border-top: 1px solid rgba(255, 255, 255, 0.1);
    flex-shrink: 0;
}

.nav-btn {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    border: none;
    background: rgba(255, 255, 255, 0.1);
    color: #fff;
    font-size: 24px;
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    justify-content: center;
}

.nav-btn:hover {
    background: #10b981;
}

.nav-counter {
    color: #fff;
    font-size: 14px;
    font-weight: 500;
    min-width: 80px;
    text-align: center;
}

/* Fit Mode Buttons */
.fit-modes {
    display: flex;
    gap: 4px;
    margin-right: 10px;
    padding-right: 10px;
    border-right: 1px solid rgba(255, 255, 255, 0.2);
}

.fit-modes button {
    padding: 8px 12px;
    font-size: 11px;
    width: auto;
}

.fit-modes button.active {
    background: #10b981;
}

/* Responsive */
@media (max-width: 767px) {
    .media-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 10px;
    }
    
    .filter-tab {
        padding: 6px 12px;
        font-size: 11px;
    }
    
    .viewer-header {
        padding: 10px 15px;
        flex-wrap: wrap;
        gap: 10px;
    }
    
    .viewer-controls {
        flex-wrap: wrap;
        gap: 5px;
    }
    
    .viewer-controls button {
        width: 36px;
        height: 36px;
        font-size: 16px;
    }
    
    .zoom-level {
        font-size: 12px;
        min-width: 40px;
    }
    
    .nav-btn {
        width: 44px;
        height: 44px;
        font-size: 20px;
    }
}

@media (max-width: 480px) {
    .media-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .media-filter-tabs {
        overflow-x: auto;
        flex-wrap: nowrap;
        padding-bottom: 10px;
    }
    
    .filter-tab {
        flex-shrink: 0;
    }
}
</style>

@section('script')
<script src="{{ asset('js/viewer.js') }}"></script>
<script>
(function() {
    // State
    var loadedImages = {};
    var currentImageIndex = 0;
    var imageList = [];
    var currentZoom = 1;
    var currentRotation = 0;
    var minZoom = 0.25;
    var maxZoom = 5;
    var zoomStep = 0.25;

    // DOM Elements
    var modal = document.getElementById('imageViewerModal');
    var viewerImage = document.getElementById('viewerImage');
    var viewerLoading = document.getElementById('viewerLoading');
    var viewerTitle = document.getElementById('viewerTitle');
    var navCounter = document.getElementById('navCounter');
    var zoomLevelDisplay = document.getElementById('zoomLevel');
    var scrollContainer = document.getElementById('viewerScrollContainer');

    // Build image list from visible items
    function buildImageList() {
        imageList = [];
        document.querySelectorAll('.media-item:not([style*="display: none"])').forEach(function(item) {
            imageList.push({
                id: item.dataset.docId,
                path: item.dataset.docPath,
                type: item.dataset.docType,
                element: item
            });
        });
    }

    // Load image from S3 via AJAX
    window.loadAndViewImage = function(element, docId) {
        var item = element.closest ? element.closest('.media-item') : element;
        var placeholder = item.querySelector('.media-placeholder');
        var placeholderContent = item.querySelector('.placeholder-content');
        var loadingSpinner = item.querySelector('.loading-spinner');

        // Show loading
        if (placeholderContent) placeholderContent.style.display = 'none';
        if (loadingSpinner) loadingSpinner.style.display = 'block';

        // Check if already loaded
        if (loadedImages[docId]) {
            // Update thumbnail
            updateThumbnail(item, docId);
            openViewer(docId);
            return;
        }

        // Fetch S3 URL via AJAX
        fetch('/api/document/' + docId + '/url', {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            },
            credentials: 'same-origin'
        })
        .then(function(response) { return response.json(); })
        .then(function(data) {
            if (data.url) {
                loadedImages[docId] = data.url;
                updateThumbnail(item, docId);
                openViewer(docId);
            }
        })
        .catch(function(error) {
            console.error('Error loading image:', error);
            if (placeholderContent) placeholderContent.style.display = 'block';
            if (loadingSpinner) loadingSpinner.style.display = 'none';
            alert('Erreur lors du chargement de l\'image');
        });
    };

    // Update thumbnail after loading
    function updateThumbnail(item, docId) {
        var placeholder = item.querySelector('.media-placeholder');
        var existingImg = item.querySelector('.media-image');
        
        if (!existingImg && loadedImages[docId]) {
            var img = document.createElement('img');
            img.src = loadedImages[docId];
            img.className = 'media-image';
            img.alt = item.dataset.docType;
            img.onclick = function() { openViewer(docId); };
            
            if (placeholder) {
                placeholder.style.display = 'none';
            }
            
            var actions = item.querySelector('.media-actions');
            if (actions) {
                item.insertBefore(img, actions);
            } else {
                item.appendChild(img);
            }
        }
    }

    // Open viewer
    function openViewer(docId) {
        buildImageList();
        
        // Find index
        currentImageIndex = imageList.findIndex(function(img) { return img.id == docId; });
        if (currentImageIndex === -1) currentImageIndex = 0;
        
        // Reset view
        currentZoom = 1;
        currentRotation = 0;
        
        showCurrentImage();
        modal.classList.add('open');
        document.body.style.overflow = 'hidden';
    }

    // Show current image in viewer
    function showCurrentImage() {
        if (imageList.length === 0) return;
        
        var current = imageList[currentImageIndex];
        viewerTitle.textContent = current.type + ' - ' + (currentImageIndex + 1) + '/' + imageList.length;
        navCounter.textContent = (currentImageIndex + 1) + ' / ' + imageList.length;
        
        // Reset zoom/rotation
        currentZoom = 1;
        currentRotation = 0;
        updateZoomDisplay();
        
        // Show loading
        viewerLoading.style.display = 'flex';
        viewerImage.style.display = 'none';
        viewerImage.style.transform = '';
        
        // Reset scroll position
        scrollContainer.scrollTop = 0;
        scrollContainer.scrollLeft = 0;
        
        // Get URL
        if (loadedImages[current.id]) {
            loadImageInViewer(loadedImages[current.id]);
        } else {
            // Fetch URL
            fetch('/api/document/' + current.id + '/url', {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                },
                credentials: 'same-origin'
            })
            .then(function(response) { return response.json(); })
            .then(function(data) {
                if (data.url) {
                    loadedImages[current.id] = data.url;
                    loadImageInViewer(data.url);
                }
            });
        }
    }

    // Load image into viewer
    function loadImageInViewer(url) {
        viewerImage.onload = function() {
            viewerLoading.style.display = 'none';
            viewerImage.style.display = 'block';
            applyTransform();
        };
        viewerImage.onerror = function() {
            viewerLoading.innerHTML = '<p style="color: #ef4444;">Erreur de chargement</p>';
        };
        viewerImage.src = url;
    }

    // Apply transform (zoom + rotation)
    function applyTransform() {
        var transform = 'scale(' + currentZoom + ') rotate(' + currentRotation + 'deg)';
        viewerImage.style.transform = transform;
        
        // Adjust container for scrolling
        if (currentRotation === 90 || currentRotation === 270) {
            // Swap dimensions when rotated 90 or 270 degrees
            scrollContainer.style.alignItems = 'flex-start';
            scrollContainer.style.justifyContent = 'flex-start';
        } else {
            scrollContainer.style.alignItems = 'flex-start';
            scrollContainer.style.justifyContent = 'flex-start';
        }
    }

    // Update zoom display
    function updateZoomDisplay() {
        zoomLevelDisplay.textContent = Math.round(currentZoom * 100) + '%';
    }

    // Close viewer
    window.closeImageViewer = function() {
        modal.classList.remove('open');
        document.body.style.overflow = '';
    };

    // Navigation
    window.viewPrevImage = function() {
        currentImageIndex = (currentImageIndex - 1 + imageList.length) % imageList.length;
        showCurrentImage();
    };

    window.viewNextImage = function() {
        currentImageIndex = (currentImageIndex + 1) % imageList.length;
        showCurrentImage();
    };

    // Zoom In
    window.zoomIn = function() {
        if (currentZoom < maxZoom) {
            currentZoom = Math.min(currentZoom + zoomStep, maxZoom);
            updateZoomDisplay();
            applyTransform();
        }
    };

    // Zoom Out
    window.zoomOut = function() {
        if (currentZoom > minZoom) {
            currentZoom = Math.max(currentZoom - zoomStep, minZoom);
            updateZoomDisplay();
            applyTransform();
        }
    };

    // Reset View
    window.resetView = function() {
        currentZoom = 1;
        currentRotation = 0;
        updateZoomDisplay();
        applyTransform();
        scrollContainer.scrollTop = 0;
        scrollContainer.scrollLeft = 0;
    };

    // Rotate
    window.rotateImage = function() {
        currentRotation = (currentRotation + 90) % 360;
        applyTransform();
    };

    // Download
    window.downloadDocument = function(docId) {
        window.open('/api/document/' + docId + '/download', '_blank');
    };

    window.downloadCurrentImage = function() {
        if (imageList.length > 0 && imageList[currentImageIndex]) {
            downloadDocument(imageList[currentImageIndex].id);
        }
    };

    // Mouse wheel zoom
    scrollContainer.addEventListener('wheel', function(e) {
        if (e.ctrlKey) {
            e.preventDefault();
            if (e.deltaY < 0) {
                zoomIn();
            } else {
                zoomOut();
            }
        }
    }, { passive: false });

    // Keyboard navigation
    document.addEventListener('keydown', function(e) {
        if (!modal.classList.contains('open')) return;
        
        switch(e.key) {
            case 'Escape': 
                closeImageViewer(); 
                break;
            case 'ArrowLeft': 
                viewPrevImage(); 
                break;
            case 'ArrowRight': 
                viewNextImage(); 
                break;
            case '+': 
            case '=': 
                e.preventDefault();
                zoomIn(); 
                break;
            case '-': 
                e.preventDefault();
                zoomOut(); 
                break;
            case 'r': 
            case 'R': 
                rotateImage(); 
                break;
            case '0':
                resetView();
                break;
        }
    });

    // Filter tabs
    document.querySelectorAll('.filter-tab').forEach(function(tab) {
        tab.addEventListener('click', function() {
            document.querySelectorAll('.filter-tab').forEach(function(t) { t.classList.remove('active'); });
            this.classList.add('active');
            
            var filter = this.dataset.filter;
            var items = document.querySelectorAll('.media-item');
            var visibleCount = 0;
            
            items.forEach(function(item) {
                if (filter === 'ALL' || item.dataset.docType === filter) {
                    item.style.display = '';
                    visibleCount++;
                } else {
                    item.style.display = 'none';
                }
            });
            
            document.getElementById('docCountBadge').textContent = visibleCount;
        });
    });

    // Delete confirmation
    document.querySelectorAll('.confirmDelete').forEach(function(btn) {
        btn.addEventListener('click', function() {
            if (confirm('Êtes-vous sûr de vouloir supprimer ce document ?')) {
                this.closest('.deleteForm').submit();
            }
        });
    });

})();
</script>
@endsection