// Script pour améliorer l'interface d'administration ECOLUX

document.addEventListener('DOMContentLoaded', function() {
    
    // Amélioration de l'aperçu des images uploadées
    function setupImagePreview() {
        const imageInputs = document.querySelectorAll('input[type="file"][accept*="image"]');
        
        imageInputs.forEach(input => {
            input.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        // Créer ou mettre à jour l'aperçu
                        let preview = input.parentNode.querySelector('.image-upload-preview');
                        if (!preview) {
                            preview = document.createElement('div');
                            preview.className = 'image-upload-preview';
                            input.parentNode.appendChild(preview);
                        }
                        
                        preview.innerHTML = `
                            <img src="${e.target.result}" 
                                 style="max-width: 200px; max-height: 150px; 
                                        border-radius: 8px; margin-top: 10px; 
                                        box-shadow: 0 2px 8px rgba(0,0,0,0.1);" />
                            <p style="font-size: 12px; color: #666; margin: 5px 0;">
                                Aperçu: ${file.name}
                            </p>
                        `;
                    };
                    reader.readAsDataURL(file);
                }
            });
        });
    }
    
    // Amélioration des champs d'ordre avec drag & drop
    function setupDragAndDrop() {
        const inlineGroups = document.querySelectorAll('.inline-group');
        
        inlineGroups.forEach(group => {
            const items = group.querySelectorAll('.inline-related');
            
            items.forEach(item => {
                item.draggable = true;
                item.style.cursor = 'move';
                
                item.addEventListener('dragstart', function(e) {
                    e.dataTransfer.setData('text/plain', '');
                    this.style.opacity = '0.5';
                });
                
                item.addEventListener('dragend', function(e) {
                    this.style.opacity = '1';
                });
                
                item.addEventListener('dragover', function(e) {
                    e.preventDefault();
                    this.style.borderTop = '3px solid #d4af37';
                });
                
                item.addEventListener('dragleave', function(e) {
                    this.style.borderTop = '';
                });
                
                item.addEventListener('drop', function(e) {
                    e.preventDefault();
                    this.style.borderTop = '';
                    // Logique de réorganisation ici
                    updateOrder(group);
                });
            });
        });
    }
    
    // Mettre à jour automatiquement les numéros d'ordre
    function updateOrder(group) {
        const orderInputs = group.querySelectorAll('input[name*="order"]');
        orderInputs.forEach((input, index) => {
            input.value = index + 1;
        });
    }
    
    // Animation pour les nouveaux éléments inline
    function animateNewInlines() {
        const addButtons = document.querySelectorAll('.add-row a');
        
        addButtons.forEach(button => {
            button.addEventListener('click', function() {
                setTimeout(() => {
                    const newInlines = document.querySelectorAll('.inline-related:last-child');
                    newInlines.forEach(inline => {
                        inline.classList.add('newly-added');
                        setTimeout(() => {
                            inline.classList.remove('newly-added');
                        }, 300);
                    });
                }, 100);
            });
        });
    }
    
    // Validation des formulaires
    function setupFormValidation() {
        const forms = document.querySelectorAll('form');
        
        forms.forEach(form => {
            form.addEventListener('submit', function(e) {
                const requiredFields = form.querySelectorAll('[required]');
                let isValid = true;
                
                requiredFields.forEach(field => {
                    if (!field.value.trim()) {
                        field.style.borderColor = '#f44336';
                        isValid = false;
                    } else {
                        field.style.borderColor = '#e0e0e0';
                    }
                });
                
                if (!isValid) {
                    e.preventDefault();
                    alert('Veuillez remplir tous les champs obligatoires.');
                }
            });
        });
    }
    
    // Amélioration des selects avec recherche
    function enhanceSelects() {
        const selects = document.querySelectorAll('select');
        
        selects.forEach(select => {
            if (select.options.length > 5) {
                select.style.background = '#f8f8f8';
                select.addEventListener('focus', function() {
                    this.style.background = '#fff';
                });
                
                select.addEventListener('blur', function() {
                    this.style.background = '#f8f8f8';
                });
            }
        });
    }
    
    // Initialisation
    setupImagePreview();
    setupDragAndDrop();
    animateNewInlines();
    setupFormValidation();
    enhanceSelects();
    
    // Ajout d'un bouton pour replier/déplier tous les fieldsets
    const collapseButton = document.createElement('button');
    collapseButton.textContent = 'Replier/Déplier tout';
    collapseButton.type = 'button';
    collapseButton.className = 'button';
    collapseButton.style.marginBottom = '20px';
    
    collapseButton.addEventListener('click', function() {
        const collapsible = document.querySelectorAll('.collapse');
        collapsible.forEach(section => {
            section.style.display = section.style.display === 'none' ? 'block' : 'none';
        });
    });
    
    const form = document.querySelector('form');
    if (form) {
        form.insertBefore(collapseButton, form.firstChild);
    }
    
    // Sauvegarde automatique des brouillons (pour les longs formulaires)
    let saveTimeout;
    const textareas = document.querySelectorAll('textarea');
    
    textareas.forEach(textarea => {
        textarea.addEventListener('input', function() {
            clearTimeout(saveTimeout);
            saveTimeout = setTimeout(() => {
                // Sauvegarder en localStorage
                const key = `draft_${window.location.pathname}_${this.name}`;
                localStorage.setItem(key, this.value);
                
                // Afficher un indicateur de sauvegarde
                let indicator = document.querySelector('.draft-saved-indicator');
                if (!indicator) {
                    indicator = document.createElement('div');
                    indicator.className = 'draft-saved-indicator';
                    indicator.style.cssText = `
                        position: fixed;
                        top: 20px;
                        right: 20px;
                        background: #4CAF50;
                        color: white;
                        padding: 10px 15px;
                        border-radius: 6px;
                        z-index: 9999;
                        font-size: 14px;
                    `;
                    document.body.appendChild(indicator);
                }
                
                indicator.textContent = 'Brouillon sauvegardé';
                indicator.style.display = 'block';
                
                setTimeout(() => {
                    indicator.style.display = 'none';
                }, 2000);
            }, 1000);
        });
        
        // Restaurer les brouillons au chargement
        const key = `draft_${window.location.pathname}_${textarea.name}`;
        const savedValue = localStorage.getItem(key);
        if (savedValue && !textarea.value) {
            textarea.value = savedValue;
        }
    });
});
