@extends('layouts.config_dashboard.app')
@section('style')
    <style>
        /* ============================================
           DOCUMENT VIEWER - ALWAYS CENTERED ROTATION
           ============================================ */
        
        .document-viewer-container {
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        }

        .viewer-header {
            background: linear-gradient(135deg, #1a1a2e 0%, #0f0f1a 100%);
            padding: 16px 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            flex-wrap: wrap;
            gap: 12px;
        }

        .viewer-title {
            display: flex;
            align-items: center;
            gap: 12px;
            color: #fff;
        }

        .viewer-title .icon {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }

        .viewer-title h5 {
            margin: 0;
            font-size: 16px;
            font-weight: 600;
        }

        .viewer-title .doc-info {
            font-size: 12px;
            color: #94a3b8;
            margin-top: 2px;
        }

        /* Quick Controls Bar */
        .quick-controls {
            display: flex;
            align-items: center;
            gap: 8px;
            flex-wrap: wrap;
        }

        .control-group {
            display: flex;
            align-items: center;
            background: rgba(255,255,255,0.1);
            border-radius: 10px;
            padding: 4px;
            gap: 2px;
        }

        .control-btn {
            width: 38px;
            height: 38px;
            border: none;
            background: transparent;
            color: #fff;
            border-radius: 8px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            transition: all 0.2s ease;
        }

        .control-btn:hover {
            background: rgba(255,255,255,0.15);
        }

        .control-btn:active {
            background: rgba(255,255,255,0.25);
            transform: scale(0.95);
        }

        .control-btn.active {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        }

        .control-btn[disabled] {
            opacity: 0.4;
            cursor: not-allowed;
        }

        .control-divider {
            width: 1px;
            height: 28px;
            background: rgba(255,255,255,0.2);
            margin: 0 8px;
        }

        .zoom-display {
            background: rgba(255,255,255,0.1);
            color: #fff;
            padding: 8px 14px;
            border-radius: 8px;
            font-size: 13px;
            font-weight: 600;
            min-width: 65px;
            text-align: center;
        }

        .rotation-display {
            background: rgba(139, 92, 246, 0.2);
            color: #a78bfa;
            padding: 8px 14px;
            border-radius: 8px;
            font-size: 13px;
            font-weight: 600;
            min-width: 50px;
            text-align: center;
        }

        .action-btn {
            padding: 10px 18px;
            border: none;
            border-radius: 8px;
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s ease;
            text-decoration: none;
        }

        .action-btn.primary {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: #fff;
        }

        .action-btn.primary:hover {
            box-shadow: 0 4px 15px rgba(16, 185, 129, 0.4);
            transform: translateY(-1px);
            color: #fff;
        }

        .action-btn.secondary {
            background: rgba(255,255,255,0.1);
            color: #fff;
        }

        .action-btn.secondary:hover {
            background: rgba(255,255,255,0.2);
            color: #fff;
        }

        .action-btn.danger {
            background: rgba(239, 68, 68, 0.2);
            color: #f87171;
        }

        .action-btn.danger:hover {
            background: #ef4444;
            color: #fff;
        }

        /* ============================================
           VIEWER BODY - FIXED CENTERING
           ============================================ */
        .viewer-body {
            position: relative;
            height: 70vh;
            min-height: 500px;
            background: #0a0a0f;
            overflow: hidden;
        }

        /* Image Stage - Full viewport centering */
        .image-stage {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: auto;
        }

        /* Image Frame - Holds the image with proper sizing */
        .image-frame {
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }

        /* The Image - Transform origin is center */
        .viewer-image {
            display: block;
            transform-origin: center center;
            transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            box-shadow: 0 10px 50px rgba(0,0,0,0.5);
            border-radius: 4px;
            cursor: grab;
            user-select: none;
            -webkit-user-drag: none;
            max-width: none;
            max-height: none;
        }

        .viewer-image:active {
            cursor: grabbing;
        }

        /* Loading State */
        .viewer-loading {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 16px;
            color: #fff;
            z-index: 10;
        }

        .viewer-loading .spinner {
            width: 48px;
            height: 48px;
            border: 3px solid rgba(255,255,255,0.1);
            border-top-color: #10b981;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        .viewer-loading.hidden {
            display: none;
        }

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

        /* Mode Toggle */
        .mode-toggle {
            display: flex;
            background: rgba(255,255,255,0.1);
            border-radius: 8px;
            padding: 4px;
        }

        .mode-toggle button {
            padding: 8px 16px;
            border: none;
            background: transparent;
            color: #94a3b8;
            border-radius: 6px;
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }

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

        .mode-toggle button:hover:not(.active) {
            color: #fff;
        }

        /* Keyboard Hints */
        .keyboard-hints {
            position: absolute;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0,0,0,0.8);
            padding: 10px 20px;
            border-radius: 8px;
            display: flex;
            gap: 20px;
            opacity: 0;
            transition: opacity 0.3s ease;
            pointer-events: none;
            z-index: 10;
        }

        .viewer-body:hover .keyboard-hints {
            opacity: 0.8;
        }

        .keyboard-hint {
            display: flex;
            align-items: center;
            gap: 6px;
            color: #94a3b8;
            font-size: 11px;
        }

        .keyboard-hint kbd {
            background: rgba(255,255,255,0.1);
            padding: 2px 6px;
            border-radius: 4px;
            font-family: monospace;
            color: #fff;
        }

        /* Status Bar */
        .status-bar {
            background: rgba(0,0,0,0.5);
            padding: 8px 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            color: #94a3b8;
            font-size: 12px;
        }

        .status-item {
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .status-item i {
            color: #10b981;
        }

        /* Editor Container */
        #editor_container {
            min-height: 70vh;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .viewer-header {
                padding: 12px 15px;
            }

            .quick-controls {
                width: 100%;
                justify-content: center;
            }

            .control-btn {
                width: 34px;
                height: 34px;
                font-size: 16px;
            }

            .action-btn span {
                display: none;
            }

            .keyboard-hints {
                display: none;
            }
        }

        /* Fullscreen Mode */
        .viewer-fullscreen {
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            right: 0 !important;
            bottom: 0 !important;
            z-index: 99999 !important;
            border-radius: 0 !important;
            margin: 0 !important;
        }

        .viewer-fullscreen .viewer-body {
            height: calc(100vh - 100px);
        }
    </style>
@endsection

@section('content')
    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-12">
                <div class="document-viewer-container" id="viewerContainer">
                    {{-- Header --}}
                    <div class="viewer-header">
                        <div class="viewer-title">
                            <div class="icon">
                                <i class="mdi mdi-file-image"></i>
                            </div>
                            <div>
                                <h5>Visualiseur de Document</h5>
                                <div class="doc-info">{{ $document->typedocument->type ?? 'Document' }} - {{ basename($document->path) }}</div>
                            </div>
                        </div>

                        <div class="quick-controls">
                            {{-- Mode Toggle --}}
                            <div class="mode-toggle">
                                <button type="button" id="viewModeBtn" class="active" title="Mode visualisation">
                                    <i class="mdi mdi-eye"></i> Voir
                                </button>
                                <button type="button" id="editModeBtn" title="Mode édition">
                                    <i class="mdi mdi-pencil"></i> Éditer
                                </button>
                            </div>

                            <div class="control-divider"></div>

                            {{-- Zoom Controls --}}
                            <div class="control-group" id="zoomControls">
                                <button type="button" class="control-btn" id="zoomOut" title="Zoom arrière (-)">
                                    <i class="mdi mdi-minus"></i>
                                </button>
                                <div class="zoom-display" id="zoomDisplay">100%</div>
                                <button type="button" class="control-btn" id="zoomIn" title="Zoom avant (+)">
                                    <i class="mdi mdi-plus"></i>
                                </button>
                                <button type="button" class="control-btn" id="zoomFit" title="Ajuster (F)">
                                    <i class="mdi mdi-fit-to-screen"></i>
                                </button>
                                <button type="button" class="control-btn" id="zoomReset" title="Reset (0)">
                                    <i class="mdi mdi-backup-restore"></i>
                                </button>
                            </div>

                            <div class="control-divider"></div>

                            {{-- Rotation Controls --}}
                            <div class="control-group" id="rotationControls">
                                <button type="button" class="control-btn" id="rotateLeft" title="Rotation gauche (L)">
                                    <i class="mdi mdi-rotate-left"></i>
                                </button>
                                <div class="rotation-display" id="rotationDisplay">0°</div>
                                <button type="button" class="control-btn" id="rotateRight" title="Rotation droite (R)">
                                    <i class="mdi mdi-rotate-right"></i>
                                </button>
                                <button type="button" class="control-btn" id="flipH" title="Retourner H (H)">
                                    <i class="mdi mdi-flip-horizontal"></i>
                                </button>
                                <button type="button" class="control-btn" id="flipV" title="Retourner V (V)">
                                    <i class="mdi mdi-flip-vertical"></i>
                                </button>
                            </div>

                            <div class="control-divider"></div>

                            {{-- Actions --}}
                            <button type="button" class="action-btn secondary" id="downloadBtn" title="Télécharger (D)">
                                <i class="mdi mdi-download"></i>
                                <span>Télécharger</span>
                            </button>
                            <button type="button" class="action-btn secondary" id="printBtn" title="Imprimer (P)">
                                <i class="mdi mdi-printer"></i>
                            </button>
                            <button type="button" class="control-btn" id="fullscreenBtn" title="Plein écran (Espace)">
                                <i class="mdi mdi-fullscreen"></i>
                            </button>
                            <a href="{{ url()->previous() }}" class="action-btn danger">
                                <i class="mdi mdi-close"></i>
                            </a>
                        </div>
                    </div>

                    {{-- Body --}}
                    <div class="viewer-body" id="viewerBody">
                        {{-- Loading --}}
                        <div class="viewer-loading" id="viewerLoading">
                            <div class="spinner"></div>
                            <span>Chargement du document...</span>
                        </div>

                        {{-- Image Stage --}}
                        <div class="image-stage" id="imageStage">
                            <div class="image-frame" id="imageFrame">
                                <img id="viewerImage" 
                                     src="{{ Storage::disk('s3')->temporaryUrl($document->path, now()->addMinutes(30)) }}" 
                                     alt="{{ $document->typedocument->type ?? 'Document' }}"
                                     class="viewer-image"
                                     draggable="false">
                            </div>
                        </div>

                        {{-- Editor Mode (hidden by default) --}}
                        <div id="editor_container" style="display: none;">
                            <img id="editor" 
                                 src="{{ Storage::disk('s3')->temporaryUrl($document->path, now()->addMinutes(30)) }}" 
                                 class="img-thumbnail" alt="">
                        </div>

                        {{-- Keyboard Hints --}}
                        <div class="keyboard-hints">
                            <span class="keyboard-hint"><kbd>+</kbd><kbd>-</kbd> Zoom</span>
                            <span class="keyboard-hint"><kbd>R</kbd><kbd>L</kbd> Rotation</span>
                            <span class="keyboard-hint"><kbd>H</kbd><kbd>V</kbd> Retourner</span>
                            <span class="keyboard-hint"><kbd>F</kbd> Ajuster</span>
                            <span class="keyboard-hint"><kbd>0</kbd> Reset</span>
                        </div>
                    </div>

                    {{-- Status Bar --}}
                    <div class="status-bar">
                        <div class="status-item">
                            <i class="mdi mdi-image-size-select-actual"></i>
                            <span id="imageDimensions">--</span>
                        </div>
                        <div class="status-item">
                            <i class="mdi mdi-rotate-right"></i>
                            <span>Rotation: <strong id="statusRotation">0°</strong></span>
                        </div>
                        <div class="status-item">
                            <i class="mdi mdi-magnify"></i>
                            <span>Zoom: <strong id="statusZoom">100%</strong></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
    <script src="https://scaleflex.cloudimg.io/v7/plugins/filerobot-image-editor/latest/filerobot-image-editor.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // ========================================
            // STATE
            // ========================================
            var state = {
                zoom: 100,
                rotation: 0,
                flipH: false,
                flipV: false,
                mode: 'view',
                editorInstance: null,
                naturalWidth: 0,
                naturalHeight: 0,
                isDragging: false,
                dragStartX: 0,
                dragStartY: 0,
                scrollStartX: 0,
                scrollStartY: 0
            };

            // Elements
            var viewerContainer = document.getElementById('viewerContainer');
            var viewerBody = document.getElementById('viewerBody');
            var imageStage = document.getElementById('imageStage');
            var imageFrame = document.getElementById('imageFrame');
            var image = document.getElementById('viewerImage');
            var loading = document.getElementById('viewerLoading');
            var zoomDisplay = document.getElementById('zoomDisplay');
            var rotationDisplay = document.getElementById('rotationDisplay');

            // ========================================
            // IMAGE LOAD
            // ========================================
            image.onload = function() {
                loading.classList.add('hidden');
                state.naturalWidth = image.naturalWidth;
                state.naturalHeight = image.naturalHeight;
                document.getElementById('imageDimensions').textContent = state.naturalWidth + ' × ' + state.naturalHeight + ' px';
                
                // Initial fit
                fitToScreen();
            };

            image.onerror = function() {
                loading.innerHTML = '<i class="mdi mdi-alert-circle" style="font-size:48px;color:#ef4444;"></i><span style="color:#f87171;">Erreur de chargement</span>';
            };

            // ========================================
            // CORE: UPDATE IMAGE SIZE AND POSITION
            // ========================================
            function updateImageDisplay() {
                var stageWidth = imageStage.clientWidth;
                var stageHeight = imageStage.clientHeight;
                
                // Determine if rotation swaps dimensions
                var isRotated90 = (state.rotation === 90 || state.rotation === 270);
                
                // Calculate scaled dimensions
                var scaledWidth = state.naturalWidth * (state.zoom / 100);
                var scaledHeight = state.naturalHeight * (state.zoom / 100);
                
                // For 90/270 rotation, the visual bounds swap
                var visualWidth = isRotated90 ? scaledHeight : scaledWidth;
                var visualHeight = isRotated90 ? scaledWidth : scaledHeight;
                
                // Set the image frame size to accommodate the rotated image
                // This ensures the image stays centered in the viewport
                imageFrame.style.width = Math.max(visualWidth, stageWidth) + 'px';
                imageFrame.style.height = Math.max(visualHeight, stageHeight) + 'px';
                imageFrame.style.minWidth = stageWidth + 'px';
                imageFrame.style.minHeight = stageHeight + 'px';
                
                // Set actual image size
                image.style.width = scaledWidth + 'px';
                image.style.height = scaledHeight + 'px';
                
                // Build transform - order matters!
                var transforms = [];
                
                // Apply rotation
                if (state.rotation !== 0) {
                    transforms.push('rotate(' + state.rotation + 'deg)');
                }
                
                // Apply flips
                if (state.flipH || state.flipV) {
                    var scaleX = state.flipH ? -1 : 1;
                    var scaleY = state.flipV ? -1 : 1;
                    transforms.push('scale(' + scaleX + ', ' + scaleY + ')');
                }
                
                image.style.transform = transforms.length > 0 ? transforms.join(' ') : 'none';
                
                // Center the scroll position
                centerScroll();
                
                // Update displays
                updateDisplays();
            }

            function centerScroll() {
                // Center the stage scroll
                var scrollX = (imageStage.scrollWidth - imageStage.clientWidth) / 2;
                var scrollY = (imageStage.scrollHeight - imageStage.clientHeight) / 2;
                imageStage.scrollLeft = Math.max(0, scrollX);
                imageStage.scrollTop = Math.max(0, scrollY);
            }

            function updateDisplays() {
                zoomDisplay.textContent = state.zoom + '%';
                rotationDisplay.textContent = state.rotation + '°';
                document.getElementById('statusZoom').textContent = state.zoom + '%';
                document.getElementById('statusRotation').textContent = state.rotation + '°';
            }

            // ========================================
            // ZOOM FUNCTIONS
            // ========================================
            function setZoom(newZoom) {
                state.zoom = Math.max(10, Math.min(500, newZoom));
                updateImageDisplay();
            }

            function fitToScreen() {
                var stageWidth = imageStage.clientWidth - 40; // padding
                var stageHeight = imageStage.clientHeight - 40;
                
                // Consider rotation for fitting
                var isRotated90 = (state.rotation === 90 || state.rotation === 270);
                var imgWidth = isRotated90 ? state.naturalHeight : state.naturalWidth;
                var imgHeight = isRotated90 ? state.naturalWidth : state.naturalHeight;
                
                var scaleX = stageWidth / imgWidth;
                var scaleY = stageHeight / imgHeight;
                var scale = Math.min(scaleX, scaleY, 1); // Don't scale up beyond 100%
                
                state.zoom = Math.round(scale * 100);
                updateImageDisplay();
            }

            document.getElementById('zoomIn').addEventListener('click', function() { 
                setZoom(state.zoom + 25); 
            });
            
            document.getElementById('zoomOut').addEventListener('click', function() { 
                setZoom(state.zoom - 25); 
            });
            
            document.getElementById('zoomReset').addEventListener('click', function() { 
                resetAll();
            });
            
            document.getElementById('zoomFit').addEventListener('click', function() {
                fitToScreen();
            });

            function resetAll() {
                state.zoom = 100;
                state.rotation = 0;
                state.flipH = false;
                state.flipV = false;
                
                document.getElementById('flipH').classList.remove('active');
                document.getElementById('flipV').classList.remove('active');
                
                fitToScreen();
            }

            // Mouse wheel zoom
            imageStage.addEventListener('wheel', function(e) {
                e.preventDefault();
                var delta = e.deltaY > 0 ? -15 : 15;
                setZoom(state.zoom + delta);
            }, { passive: false });

            // ========================================
            // ROTATION FUNCTIONS
            // ========================================
            function setRotation(angle) {
                // Normalize angle to 0, 90, 180, 270
                state.rotation = ((angle % 360) + 360) % 360;
                updateImageDisplay();
            }

            document.getElementById('rotateLeft').addEventListener('click', function() {
                setRotation(state.rotation - 90);
            });

            document.getElementById('rotateRight').addEventListener('click', function() {
                setRotation(state.rotation + 90);
            });

            document.getElementById('flipH').addEventListener('click', function() {
                state.flipH = !state.flipH;
                this.classList.toggle('active', state.flipH);
                updateImageDisplay();
            });

            document.getElementById('flipV').addEventListener('click', function() {
                state.flipV = !state.flipV;
                this.classList.toggle('active', state.flipV);
                updateImageDisplay();
            });

            // ========================================
            // DRAG TO PAN
            // ========================================
            imageStage.addEventListener('mousedown', function(e) {
                if (e.target !== image && e.target !== imageFrame) return;
                state.isDragging = true;
                imageStage.style.cursor = 'grabbing';
                state.dragStartX = e.pageX;
                state.dragStartY = e.pageY;
                state.scrollStartX = imageStage.scrollLeft;
                state.scrollStartY = imageStage.scrollTop;
                e.preventDefault();
            });

            document.addEventListener('mousemove', function(e) {
                if (!state.isDragging) return;
                var dx = e.pageX - state.dragStartX;
                var dy = e.pageY - state.dragStartY;
                imageStage.scrollLeft = state.scrollStartX - dx;
                imageStage.scrollTop = state.scrollStartY - dy;
            });

            document.addEventListener('mouseup', function() {
                if (state.isDragging) {
                    state.isDragging = false;
                    imageStage.style.cursor = 'grab';
                }
            });

            // Set initial cursor
            imageStage.style.cursor = 'grab';

            // ========================================
            // MODE TOGGLE
            // ========================================
            document.getElementById('viewModeBtn').addEventListener('click', function() {
                if (state.mode === 'view') return;
                state.mode = 'view';
                this.classList.add('active');
                document.getElementById('editModeBtn').classList.remove('active');
                imageStage.style.display = 'flex';
                document.getElementById('editor_container').style.display = 'none';
                document.getElementById('zoomControls').style.display = 'flex';
                document.getElementById('rotationControls').style.display = 'flex';
                
                if (state.editorInstance) {
                    state.editorInstance.terminate();
                    state.editorInstance = null;
                }
            });

            document.getElementById('editModeBtn').addEventListener('click', function() {
                if (state.mode === 'edit') return;
                state.mode = 'edit';
                this.classList.add('active');
                document.getElementById('viewModeBtn').classList.remove('active');
                imageStage.style.display = 'none';
                document.getElementById('editor_container').style.display = 'block';
                document.getElementById('zoomControls').style.display = 'none';
                document.getElementById('rotationControls').style.display = 'none';
                
                initEditor();
            });

            // ========================================
            // FILEROBOT EDITOR
            // ========================================
            function initEditor() {
                if (state.editorInstance) return;

                var imgSrc = document.getElementById('editor').src;
                var { TABS, TOOLS } = FilerobotImageEditor;

                var config = {
                    source: imgSrc,
                    onSave: function(editedImageObject, designState) {
                        console.log('Saved:', editedImageObject);
                        alert('Image modifiée! Téléchargez pour sauvegarder.');
                    },
                    annotationsCommon: {
                        fill: '#ff0000',
                    },
                    Text: {
                        text: '{{ $document->dossier->ref ?? "Texte" }}'
                    },
                    Rotate: {
                        angle: 90,
                        componentType: 'slider'
                    },
                    tabsIds: [TABS.ADJUST, TABS.ANNOTATE, TABS.FILTERS, TABS.FINETUNE],
                    defaultTabId: TABS.ADJUST,
                    defaultToolId: TOOLS.ROTATE,
                    theme: {
                        palette: {
                            'bg-primary': '#1a1a2e',
                            'bg-secondary': '#16213e',
                            'accent-primary': '#10b981',
                            'accent-primary-hover': '#059669',
                            'txt-primary': '#ffffff',
                            'txt-secondary': '#94a3b8',
                            'border': 'rgba(255,255,255,0.1)'
                        }
                    }
                };

                state.editorInstance = new FilerobotImageEditor(
                    document.querySelector('#editor_container'),
                    config
                );

                state.editorInstance.render({
                    onClose: function(closingReason) {
                        console.log('Editor closed:', closingReason);
                    }
                });
            }

            // ========================================
            // DOWNLOAD
            // ========================================
            document.getElementById('downloadBtn').addEventListener('click', function() {
                var link = document.createElement('a');
                link.href = image.src;
                link.download = '{{ basename($document->path) }}';
                link.target = '_blank';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            });

            // ========================================
            // PRINT
            // ========================================
            document.getElementById('printBtn').addEventListener('click', function() {
                var printWindow = window.open('', '_blank');
                var transformStyle = 'transform: rotate(' + state.rotation + 'deg)';
                if (state.flipH) transformStyle += ' scaleX(-1)';
                if (state.flipV) transformStyle += ' scaleY(-1)';
                transformStyle += ';';
                
                printWindow.document.write('<html><head><title>Imprimer</title></head><body style="margin:0;display:flex;justify-content:center;align-items:center;min-height:100vh;background:#fff;">');
                printWindow.document.write('<img src="' + image.src + '" style="max-width:100%;max-height:100vh;' + transformStyle + '" onload="window.print();window.close();">');
                printWindow.document.write('</body></html>');
                printWindow.document.close();
            });

            // ========================================
            // FULLSCREEN
            // ========================================
            document.getElementById('fullscreenBtn').addEventListener('click', toggleFullscreen);

            function toggleFullscreen() {
                if (!document.fullscreenElement) {
                    viewerContainer.requestFullscreen().catch(function(err) {
                        console.error('Fullscreen error:', err);
                    });
                    viewerContainer.classList.add('viewer-fullscreen');
                    document.getElementById('fullscreenBtn').innerHTML = '<i class="mdi mdi-fullscreen-exit"></i>';
                } else {
                    document.exitFullscreen();
                    viewerContainer.classList.remove('viewer-fullscreen');
                    document.getElementById('fullscreenBtn').innerHTML = '<i class="mdi mdi-fullscreen"></i>';
                }
            }

            document.addEventListener('fullscreenchange', function() {
                if (!document.fullscreenElement) {
                    viewerContainer.classList.remove('viewer-fullscreen');
                    document.getElementById('fullscreenBtn').innerHTML = '<i class="mdi mdi-fullscreen"></i>';
                }
                // Re-fit after fullscreen change
                setTimeout(fitToScreen, 100);
            });

            // ========================================
            // KEYBOARD SHORTCUTS
            // ========================================
            document.addEventListener('keydown', function(e) {
                if (state.mode === 'edit') return;
                if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
                
                switch(e.key) {
                    case '+':
                    case '=':
                        e.preventDefault();
                        setZoom(state.zoom + 25);
                        break;
                    case '-':
                        e.preventDefault();
                        setZoom(state.zoom - 25);
                        break;
                    case '0':
                        e.preventDefault();
                        resetAll();
                        break;
                    case 'f':
                    case 'F':
                        e.preventDefault();
                        fitToScreen();
                        break;
                    case 'r':
                    case 'R':
                        e.preventDefault();
                        setRotation(state.rotation + 90);
                        break;
                    case 'l':
                    case 'L':
                        e.preventDefault();
                        setRotation(state.rotation - 90);
                        break;
                    case 'h':
                    case 'H':
                        e.preventDefault();
                        document.getElementById('flipH').click();
                        break;
                    case 'v':
                    case 'V':
                        e.preventDefault();
                        document.getElementById('flipV').click();
                        break;
                    case 'd':
                    case 'D':
                        e.preventDefault();
                        document.getElementById('downloadBtn').click();
                        break;
                    case 'p':
                    case 'P':
                        e.preventDefault();
                        document.getElementById('printBtn').click();
                        break;
                    case ' ':
                        e.preventDefault();
                        toggleFullscreen();
                        break;
                    case 'Escape':
                        if (document.fullscreenElement) {
                            document.exitFullscreen();
                        }
                        break;
                }
            });

            // ========================================
            // TOUCH SUPPORT
            // ========================================
            var touchStartDist = 0;
            var touchStartZoom = 100;

            imageStage.addEventListener('touchstart', function(e) {
                if (e.touches.length === 2) {
                    var dx = e.touches[0].pageX - e.touches[1].pageX;
                    var dy = e.touches[0].pageY - e.touches[1].pageY;
                    touchStartDist = Math.hypot(dx, dy);
                    touchStartZoom = state.zoom;
                }
            }, { passive: true });

            imageStage.addEventListener('touchmove', function(e) {
                if (e.touches.length === 2) {
                    var dx = e.touches[0].pageX - e.touches[1].pageX;
                    var dy = e.touches[0].pageY - e.touches[1].pageY;
                    
                    // Pinch zoom
                    var dist = Math.hypot(dx, dy);
                    var scale = dist / touchStartDist;
                    setZoom(Math.round(touchStartZoom * scale));
                }
            }, { passive: true });

            // ========================================
            // WINDOW RESIZE
            // ========================================
            var resizeTimeout;
            window.addEventListener('resize', function() {
                clearTimeout(resizeTimeout);
                resizeTimeout = setTimeout(function() {
                    updateImageDisplay();
                }, 100);
            });
        });
    </script>
@endsection