// js/main.js

/**
 * Bildvorschau vor dem Upload
 */
function initImagePreview() {
    const fileInputs = document.querySelectorAll('input[type="file"][accept*="image"]');
    
    fileInputs.forEach(input => {
        input.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (!file) return;
            
            // Prüfe Dateigröße (5MB)
            const maxSize = 5 * 1024 * 1024;
            if (file.size > maxSize) {
                alert('Datei ist zu groß! Maximum: 5 MB');
                this.value = '';
                return;
            }
            
            // Erstelle Vorschau
            const reader = new FileReader();
            reader.onload = function(event) {
                // Suche oder erstelle Vorschau-Container
                let previewContainer = input.parentElement.querySelector('.image-preview-container');
                
                if (!previewContainer) {
                    previewContainer = document.createElement('div');
                    previewContainer.className = 'image-preview-container';
                    input.parentElement.appendChild(previewContainer);
                }
                
                previewContainer.innerHTML = `
                    <div class="image-preview">
                        <img src="${event.target.result}" alt="Vorschau">
                        <button type="button" class="btn btn-small btn-danger" onclick="clearImagePreview(this)">
                            Entfernen
                        </button>
                    </div>
                `;
            };
            reader.readAsDataURL(file);
        });
    });
}

/**
 * Bildvorschau entfernen
 */
function clearImagePreview(button) {
    const container = button.closest('.image-preview-container');
    const fileInput = container.parentElement.querySelector('input[type="file"]');
    
    if (fileInput) fileInput.value = '';
    container.remove();
}

/**
 * Sortierbare Tabellen
 */
function initSortableTables() {
    const tables = document.querySelectorAll('.data-table');
    
    tables.forEach(table => {
        const headers = table.querySelectorAll('th');
        
        headers.forEach((header, index) => {
            // Überspringe Bild- und Aktionen-Spalten
            if (header.textContent.includes('Bild') || header.textContent.includes('Aktionen')) {
                return;
            }
            
            header.style.cursor = 'pointer';
            header.title = 'Klicken zum Sortieren';
            
            // Füge Sortier-Icon hinzu
            const icon = document.createElement('span');
            icon.className = 'sort-icon';
            icon.innerHTML = ' ⇅';
            header.appendChild(icon);
            
            header.addEventListener('click', () => {
                sortTable(table, index);
            });
        });
    });
}

/**
 * Tabelle sortieren
 */
function sortTable(table, columnIndex) {
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    
    // Prüfe ob schon sortiert wurde
    const header = table.querySelectorAll('th')[columnIndex];
    const currentOrder = header.dataset.order || 'asc';
    const newOrder = currentOrder === 'asc' ? 'desc' : 'asc';
    
    // Entferne alle Sortier-Markierungen
    table.querySelectorAll('th').forEach(th => {
        th.dataset.order = '';
        const icon = th.querySelector('.sort-icon');
        if (icon) icon.innerHTML = ' ⇅';
    });
    
    // Setze neue Sortierung
    header.dataset.order = newOrder;
    const icon = header.querySelector('.sort-icon');
    if (icon) icon.innerHTML = newOrder === 'asc' ? ' ↑' : ' ↓';
    
    // Sortiere Zeilen
    rows.sort((a, b) => {
        const aValue = a.cells[columnIndex].textContent.trim();
        const bValue = b.cells[columnIndex].textContent.trim();
        
        // Prüfe ob Zahlen (Preis)
        const aNum = parseFloat(aValue.replace(/[^\d,-]/g, '').replace(',', '.'));
        const bNum = parseFloat(bValue.replace(/[^\d,-]/g, '').replace(',', '.'));
        
        if (!isNaN(aNum) && !isNaN(bNum)) {
            return newOrder === 'asc' ? aNum - bNum : bNum - aNum;
        }
        
        // Text-Sortierung
        return newOrder === 'asc' 
            ? aValue.localeCompare(bValue, 'de')
            : bValue.localeCompare(aValue, 'de');
    });
    
    // Zeilen neu einfügen
    rows.forEach(row => tbody.appendChild(row));
}

/**
 * Bestätigungs-Dialoge
 * Hinweis: Für Orte und Kategorien wird onsubmit im HTML verwendet
 * Hier nur für Links zu delete.php (Haupttabelle)
 */
function initConfirmDialogs() {
    const deleteLinks = document.querySelectorAll('a[href*="delete.php"]');
    
    deleteLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            if (!this.hasAttribute('data-confirmed')) {
                e.preventDefault();
                
                const confirmed = confirm('Möchten Sie diesen Eintrag wirklich löschen?');
                
                if (confirmed) {
                    this.setAttribute('data-confirmed', 'true');
                    this.click();
                }
            }
        });
    });
}

/**
 * Auto-Save für Filter
 */
function initFilterMemory() {
    const filterForm = document.querySelector('.filter-form');
    if (!filterForm) return;
    
    // Lade gespeicherte Filter
    const savedFilters = localStorage.getItem('inventar_filter');
    if (savedFilters) {
        try {
            const filters = JSON.parse(savedFilters);
            Object.keys(filters).forEach(key => {
                const input = filterForm.querySelector(`[name="${key}"]`);
                if (input && !input.value) {
                    input.value = filters[key];
                }
            });
        } catch (e) {
            console.error('Fehler beim Laden der Filter:', e);
        }
    }
    
    // Speichere Filter bei Änderung
    filterForm.addEventListener('submit', function() {
        const formData = new FormData(this);
        const filters = {};
        
        formData.forEach((value, key) => {
            if (value) filters[key] = value;
        });
        
        localStorage.setItem('inventar_filter', JSON.stringify(filters));
    });
    
    // Reset-Button löscht auch gespeicherte Filter
    const resetBtn = filterForm.querySelector('a[href="index.php"]');
    if (resetBtn) {
        resetBtn.addEventListener('click', function() {
            localStorage.removeItem('inventar_filter');
        });
    }
}

/**
 * Ladeanzeige für Formulare
 */
function initLoadingIndicators() {
    const forms = document.querySelectorAll('form');
    
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            const submitBtn = this.querySelector('button[type="submit"]');
            
            if (submitBtn && !submitBtn.disabled) {
                submitBtn.disabled = true;
                submitBtn.dataset.originalText = submitBtn.textContent;
                submitBtn.textContent = 'Bitte warten...';
                
                // Falls Formular nicht abgesendet wird (Validierung fehlgeschlagen)
                setTimeout(() => {
                    if (submitBtn.disabled) {
                        submitBtn.disabled = false;
                        submitBtn.textContent = submitBtn.dataset.originalText;
                    }
                }, 5000);
            }
        });
    });
}

/**
 * Tooltips
 */
function initTooltips() {
    const elements = document.querySelectorAll('[title]');
    
    elements.forEach(element => {
        element.addEventListener('mouseenter', function(e) {
            const title = this.getAttribute('title');
            if (!title) return;
            
            // Erstelle Tooltip
            const tooltip = document.createElement('div');
            tooltip.className = 'custom-tooltip';
            tooltip.textContent = title;
            document.body.appendChild(tooltip);
            
            // Positioniere Tooltip
            const rect = this.getBoundingClientRect();
            tooltip.style.left = rect.left + (rect.width / 2) - (tooltip.offsetWidth / 2) + 'px';
            tooltip.style.top = rect.bottom + 5 + 'px';
            
            // Speichere Referenz
            this.dataset.tooltipId = Date.now();
            tooltip.dataset.tooltipId = this.dataset.tooltipId;
        });
        
        element.addEventListener('mouseleave', function() {
            const tooltips = document.querySelectorAll('.custom-tooltip');
            tooltips.forEach(t => {
                if (t.dataset.tooltipId === this.dataset.tooltipId) {
                    t.remove();
                }
            });
        });
    });
}

/**
 * Zeichenzähler für Textareas
 */
function initCharacterCounters() {
    const textareas = document.querySelectorAll('textarea[maxlength]');
    
    textareas.forEach(textarea => {
        const maxLength = textarea.getAttribute('maxlength');
        
        // Erstelle Counter
        const counter = document.createElement('div');
        counter.className = 'character-counter';
        counter.textContent = `0 / ${maxLength}`;
        textarea.parentElement.appendChild(counter);
        
        // Update Counter
        const updateCounter = () => {
            const length = textarea.value.length;
            counter.textContent = `${length} / ${maxLength}`;
            counter.style.color = length > maxLength * 0.9 ? '#e74c3c' : '#666';
        };
        
        textarea.addEventListener('input', updateCounter);
        updateCounter();
    });
}

/**
 * Schnellsuche mit Highlight
 */
function initQuickSearch() {
    const searchInput = document.querySelector('input[name="search"]');
    if (!searchInput) return;
    
    let searchTimeout;
    
    searchInput.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        
        const query = this.value.toLowerCase().trim();
        
        if (query.length === 0) {
            // Zeige alle Zeilen
            document.querySelectorAll('.data-table tbody tr').forEach(row => {
                row.style.display = '';
                row.querySelectorAll('.highlight').forEach(el => {
                    el.outerHTML = el.textContent;
                });
            });
            return;
        }
        
        searchTimeout = setTimeout(() => {
            const rows = document.querySelectorAll('.data-table tbody tr');
            
            rows.forEach(row => {
                const text = row.textContent.toLowerCase();
                
                if (text.includes(query)) {
                    row.style.display = '';
                    
                    // Highlight Suchbegriff
                    row.querySelectorAll('td').forEach(cell => {
                        if (cell.classList.contains('td-image') || cell.classList.contains('td-actions')) {
                            return;
                        }
                        
                        const cellText = cell.textContent;
                        const cellTextLower = cellText.toLowerCase();
                        
                        if (cellTextLower.includes(query)) {
                            const regex = new RegExp(`(${query})`, 'gi');
                            cell.innerHTML = cellText.replace(regex, '<mark class="highlight">$1</mark>');
                        }
                    });
                } else {
                    row.style.display = 'none';
                }
            });
        }, 300);
    });
}

/**
 * Responsive Tabellen-Scroll-Hint
 */
function initScrollHint() {
    const tableContainers = document.querySelectorAll('.table-responsive');
    
    tableContainers.forEach(container => {
        const table = container.querySelector('table');
        
        if (table && table.offsetWidth > container.offsetWidth) {
            const hint = document.createElement('div');
            hint.className = 'scroll-hint';
            hint.innerHTML = '← Scrollen →';
            container.appendChild(hint);
            
            // Entferne Hint nach Scroll
            container.addEventListener('scroll', function() {
                hint.style.display = 'none';
            }, { once: true });
        }
    });
}

/**
 * Initialisierung aller Features
 */
document.addEventListener('DOMContentLoaded', function() {
    initImagePreview();
    initSortableTables();
    initConfirmDialogs();
    initFilterMemory();
    initLoadingIndicators();
    initTooltips();
    initCharacterCounters();
    initQuickSearch();
    initScrollHint();
    
    console.log('✓ Wertsachen-Inventar geladen');
});

/**
 * Service Worker für PWA (Progressive Web App)
 */
if ('serviceWorker' in navigator) {
    window.addEventListener('load', function() {
        navigator.serviceWorker.register('/service-worker.js')
            .then(reg => console.log('✓ Service Worker registriert'))
            .catch(err => console.log('Service Worker Fehler:', err));
    });
}