document.addEventListener('DOMContentLoaded', function() {
    // DOM Elements
    const backgroundInput = document.getElementById('background');
    const canvasContainer = document.getElementById('canvas-container');
    const dropZone = document.getElementById('drop-zone');
    const backgroundImage = document.getElementById('background-image');
    const qrContainer = document.getElementById('qr-container');
    const addQRBtn = document.getElementById('addQR');
    const clearAllBtn = document.getElementById('clearAll');
    const generateBtn = document.getElementById('generateBtn');
    const showTextCheckbox = document.getElementById('showText');
    const textColorContainer = document.getElementById('textColorContainer');
    const progressContainer = document.getElementById('progress-container');
    const progressBar = document.getElementById('progress-bar');
    const progressText = document.getElementById('progress-text');
    const contextMenu = document.getElementById('context-menu');
    const duplicateQrBtn = document.getElementById('duplicate-qr');
    const deleteQrBtn = document.getElementById('delete-qr');
    
    let currentImageUrl = null;
    let activeQr = null;
    let qrCounter = 0;
    let qrElements = [];
    
    // Initialize interact.js
    if (typeof interact === 'undefined') {
        console.error('Interact.js not loaded');
        return;
    }
    
    // Event Listeners
    backgroundInput.addEventListener('change', handleFileUpload);
    dropZone.addEventListener('click', () => backgroundInput.click());
    dropZone.addEventListener('dragover', handleDragOver);
    dropZone.addEventListener('drop', handleDrop);
    addQRBtn.addEventListener('click', addNewQR);
    clearAllBtn.addEventListener('click', clearAllQRs);
    generateBtn.addEventListener('click', generateImages);
    showTextCheckbox.addEventListener('change', toggleTextColor);
    document.addEventListener('click', closeContextMenu);
    duplicateQrBtn.addEventListener('click', duplicateActiveQR);
    deleteQrBtn.addEventListener('click', deleteActiveQR);
    
    // Toggle text color input based on checkbox
    function toggleTextColor() {
        textColorContainer.style.display = showTextCheckbox.checked ? 'block' : 'none';
    }
    
    // Handle file upload
    function handleFileUpload(e) {
        const file = e.target.files[0];
        if (!file) return;
        
        if (!file.type.match('image.*')) {
            showError('Please upload an image file');
            return;
        }
        
        uploadImage(file);
    }
    
    // Handle drag over
    function handleDragOver(e) {
        e.preventDefault();
        e.stopPropagation();
        dropZone.style.backgroundColor = 'rgba(0, 123, 255, 0.1)';
    }
    
    // Handle drop
    function handleDrop(e) {
        e.preventDefault();
        e.stopPropagation();
        dropZone.style.backgroundColor = '';
        
        const file = e.dataTransfer.files[0];
        if (!file) return;
        
        if (!file.type.match('image.*')) {
            showError('Please upload an image file');
            return;
        }
        
        backgroundInput.files = e.dataTransfer.files;
        uploadImage(file);
    }
    
    // Upload image to server
    function uploadImage(file) {
        const formData = new FormData();
        formData.append('background', file);
        
        fetch('/upload', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                showError(data.error);
                return;
            }
            
            // Display the uploaded image
            displayBackgroundImage(data.url);
            currentImageUrl = data.filename;
        })
        .catch(error => {
            console.error('Error:', error);
            showError('Failed to upload image');
        });
    }
    
    // Display background image
    function displayBackgroundImage(url) {
        backgroundImage.src = url;
        backgroundImage.classList.remove('d-none');
        dropZone.classList.add('d-none');
        
        // Wait for image to load
        backgroundImage.onload = function() {
            // Set canvas container dimensions
            const maxWidth = canvasContainer.offsetWidth;
            const ratio = Math.min(maxWidth / this.naturalWidth, 1);
            const displayWidth = this.naturalWidth * ratio;
            const displayHeight = this.naturalHeight * ratio;
            
            backgroundImage.style.width = `${displayWidth}px`;
            backgroundImage.style.height = `${displayHeight}px`;
            canvasContainer.style.height = `${displayHeight}px`;
        };
    }
    
    // Add new QR code
    function addNewQR() {
        if (!currentImageUrl) {
            showError('Please upload an image first');
            return;
        }
        
        const qrId = `qr-${qrCounter++}`;
        const qrElement = document.createElement('div');
        qrElement.className = 'qr-item';
        qrElement.id = qrId;
        qrElement.dataset.width = '100';
        qrElement.dataset.height = '100';
        
        // Position in center
        const containerRect = canvasContainer.getBoundingClientRect();
        const left = (containerRect.width - 100) / 2;
        const top = (containerRect.height - 100) / 2;
        
        qrElement.style.width = '100px';
        qrElement.style.height = '100px';
        qrElement.style.left = `${left}px`;
        qrElement.style.top = `${top}px`;
        
        // Add resize handle
        const resizeHandle = document.createElement('div');
        resizeHandle.className = 'qr-resize-handle';
        qrElement.appendChild(resizeHandle);
        
        // Add to container
        qrContainer.appendChild(qrElement);
        qrElements.push(qrElement);
        
        // Make draggable and resizable
        setupInteract(qrElement);
        
        // Set active
        setActiveQR(qrElement);
    }
    
    // Set active QR
    function setActiveQR(qrElement) {
        // Remove active class from all
        qrElements.forEach(qr => qr.classList.remove('active'));
        
        // Set new active
        qrElement.classList.add('active');
        activeQr = qrElement;
    }
    
    // Setup interact.js for a QR element
    function setupInteract(qrElement) {
        // Drag functionality
        interact(qrElement).draggable({
            inertia: true,
            modifiers: [
                interact.modifiers.restrictRect({
                    restriction: 'parent',
                    endOnly: true
                })
            ],
            autoScroll: true,
            listeners: {
                start(event) {
                    setActiveQR(event.target);
                },
                move(event) {
                    const target = event.target;
                    const x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx;
                    const y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
                    
                    target.style.transform = `translate(${x}px, ${y}px)`;
                    target.setAttribute('data-x', x);
                    target.setAttribute('data-y', y);
                }
            }
        });
        
        // Resize functionality
        interact(qrElement).resizable({
            edges: { right: true, bottom: true },
            listeners: {
                start(event) {
                    setActiveQR(event.target);
                event.target.dataset.prevWidth = event.rect.width;
                    event.target.dataset.prevHeight = event.rect.height;
                },
                move(event) {
                    const target = event.target;
                    let width = parseFloat(target.dataset.width) || parseFloat(target.dataset.prevWidth);
                    let height = parseFloat(target.dataset.height) || parseFloat(target.dataset.prevHeight);
                    
                    width = event.rect.width;
                    height = event.rect.height;
                    
                    target.style.width = `${width}px`;
                    target.style.height = `${height}px`;
                    target.dataset.width = width;
                    target.dataset.height = height;
                }
            },
            modifiers: [
                interact.modifiers.aspectRatio({
                    ratio: 'preserve'
                })
            ]
        });
        
        // Context menu
        qrElement.addEventListener('contextmenu', function(e) {
            e.preventDefault();
            setActiveQR(e.target);
            showContextMenu(e.clientX, e.clientY);
        });
        
        // Click to select
        qrElement.addEventListener('click', function(e) {
            e.stopPropagation();
            setActiveQR(e.target);
        });
    }
    
    // Show context menu
    function showContextMenu(x, y) {
        contextMenu.style.display = 'block';
        contextMenu.style.left = `${x}px`;
        contextMenu.style.top = `${y}px`;
    }
    
    // Close context menu
    function closeContextMenu(e) {
        if (e.target !== duplicateQrBtn && e.target !== deleteQrBtn) {
            contextMenu.style.display = 'none';
        }
    }
    
    // Duplicate active QR
    function duplicateActiveQR() {
        if (!activeQr) return;
        
        const qrId = `qr-${qrCounter++}`;
        const qrElement = document.createElement('div');
        qrElement.className = 'qr-item';
        qrElement.id = qrId;
        qrElement.dataset.width = activeQr.dataset.width;
        qrElement.dataset.height = activeQr.dataset.height;
        
        // Position offset from original
        const rect = activeQr.getBoundingClientRect();
        const offset = 20;
        
        qrElement.style.width = `${activeQr.dataset.width}px`;
        qrElement.style.height = `${activeQr.dataset.height}px`;
        qrElement.style.left = `${parseFloat(activeQr.style.left) + offset}px`;
        qrElement.style.top = `${parseFloat(activeQr.style.top) + offset}px`;
        
        // Add resize handle
        const resizeHandle = document.createElement('div');
        resizeHandle.className = 'qr-resize-handle';
        qrElement.appendChild(resizeHandle);
        
        // Add to container
        qrContainer.appendChild(qrElement);
        qrElements.push(qrElement);
        
        // Make draggable and resizable
        setupInteract(qrElement);
        
        // Set active
        setActiveQR(qrElement);
        
        // Hide context menu
        contextMenu.style.display = 'none';
    }
    
    // Delete active QR
    function deleteActiveQR() {
        if (!activeQr) return;
        
        const index = qrElements.indexOf(activeQr);
        if (index > -1) {
            qrElements.splice(index, 1);
        }
        
        qrContainer.removeChild(activeQr);
        activeQr = null;
        contextMenu.style.display = 'none';
    }
    
    // Clear all QR codes
    function clearAllQRs() {
        qrElements.forEach(qr => qrContainer.removeChild(qr));
        qrElements = [];
        activeQr = null;
    }
    
    // Generate images
    function generateImages() {
        // Validate inputs
        if (!currentImageUrl) {
            showError('Please upload an image first');
            return;
        }
        
        const startNum = parseInt(document.getElementById('startNum').value);
        const endNum = parseInt(document.getElementById('endNum').value);
        const increment = parseInt(document.getElementById('increment').value);
        
        if (isNaN(startNum) || isNaN(endNum) || isNaN(increment) || 
            startNum < 1 || endNum < startNum || increment < 1) {
            showError('Invalid numbering parameters');
            return;
        }
        
        if (qrElements.length === 0) {
            showError('Please add at least one QR code');
            return;
        }
        
        // Prepare QR data
        const qrData = qrElements.map(qr => {
            const rect = qr.getBoundingClientRect();
            const containerRect = canvasContainer.getBoundingClientRect();
            
            return {
                x: rect.left - containerRect.left,
                y: rect.top - containerRect.top,
                width: rect.width,
                height: rect.height
            };
        });
        
        // Show progress
        progressContainer.classList.remove('d-none');
        progressBar.style.width = '0%';
        progressText.textContent = 'Preparing files...';
        
        // Disable generate button
        generateBtn.disabled = true;
        
        // Send request to server
        fetch('/generate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                image: currentImageUrl,
                qrData: qrData,
                startNum: startNum,
                endNum: endNum,
                increment: increment,
                showText: showTextCheckbox.checked,
                qrColor: document.getElementById('qrColor').value,
                bgColor: document.getElementById('bgColor').value,
                textColor: document.getElementById('textColor').value
            })
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(err => { throw new Error(err.error || 'Generation failed'); });
            }
            return response.blob();
        })
        .then(blob => {
            // Create download link
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'qr_images.zip';
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
            
            // Update progress
            progressBar.style.width = '100%';
            progressText.textContent = 'Download complete!';
            
            // Re-enable button after delay
            setTimeout(() => {
                progressContainer.classList.add('d-none');
                generateBtn.disabled = false;
            }, 2000);
        })
        .catch(error => {
            console.error('Error:', error);
            showError(error.message);
            progressContainer.classList.add('d-none');
            generateBtn.disabled = false;
        });
    }
    
    // Show error message
    function showError(message) {
        const alert = document.createElement('div');
        alert.className = 'alert alert-danger alert-dismissible fade show';
        alert.role = 'alert';
        alert.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        `;
        
        const container = document.querySelector('.card-body');
        container.insertBefore(alert, container.firstChild);
        
        // Auto-dismiss after 5 seconds
        setTimeout(() => {
            alert.classList.remove('show');
            setTimeout(() => alert.remove(), 150);
        }, 5000);
    }
    
    // Initialize
    toggleTextColor();
});