import './bootstrap';
import './bbcode';
import * as CodeMirror from 'codemirror';


class AdminPanel {
    constructor() {
        this.init();
    }

    init() {
        // Wait for DOM to be ready
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.initializeComponents());
        } else {
            this.initializeComponents();
        }
    }

    initializeComponents() {
        console.log('Initializing Admin Panel Components');
        
        this.initializeSidebar();
        this.initializeDropdowns();
        this.initializeTabNavigation();
        this.initializeFormHandlers();
        this.initializeSpecialInputs();
        this.initializeColorPickers();
        this.initializeIconPickers();
        this.initializeAlerts();
        this.initializeCodeEditors();
        this.initializePluginManagement();
        
        console.log('Admin Panel initialized successfully');
    }
    
    initializeSidebar() {
        const sidebarToggle = document.getElementById('sidebarToggle');
        const menuToggle = document.getElementById('menuToggle');
        const adminSidebar = document.querySelector('.admin-sidebar');
        const adminMain = document.querySelector('.admin-main');
        
        // Desktop sidebar toggle
        if (sidebarToggle && adminSidebar && adminMain) {
            sidebarToggle.addEventListener('click', () => {
                adminSidebar.classList.toggle('collapsed');
                adminMain.classList.toggle('expanded');
                
                // Store preference in localStorage
                localStorage.setItem('sidebar-collapsed', adminSidebar.classList.contains('collapsed'));
            });
            
            // Restore sidebar state from localStorage
            const isCollapsed = localStorage.getItem('sidebar-collapsed') === 'true';
            if (isCollapsed) {
                adminSidebar.classList.add('collapsed');
                adminMain.classList.add('expanded');
            }
        }
        
        // Mobile menu toggle
        if (menuToggle && adminSidebar) {
            menuToggle.addEventListener('click', (e) => {
                e.stopPropagation();
                adminSidebar.classList.toggle('mobile-active');
            });
        }
        
        // Close mobile sidebar when clicking outside
        if (adminSidebar && menuToggle) {
            document.addEventListener('click', (event) => {
                if (window.innerWidth < 992) {
                    const clickInsideSidebar = adminSidebar.contains(event.target);
                    const clickOnMenuToggle = menuToggle.contains(event.target);
                    
                    if (!clickInsideSidebar && !clickOnMenuToggle && adminSidebar.classList.contains('mobile-active')) {
                        adminSidebar.classList.remove('mobile-active');
                    }
                }
            });
        }

        // Handle sidebar navigation active states
        this.initializeSidebarNavigation();
    }

    initializeSidebarNavigation() {
        const navLinks = document.querySelectorAll('.sidebar-nav a');
        const currentPath = window.location.pathname;
        
        navLinks.forEach(link => {
            const href = link.getAttribute('href');
            if (href && (href === currentPath || currentPath.startsWith(href + '/'))) {
                // Remove active class from all links
                navLinks.forEach(l => l.parentElement.classList.remove('active'));
                // Add active class to current link
                link.parentElement.classList.add('active');
            }
        });
    }
    
    initializeDropdowns() {
        const notificationBtn = document.querySelector('.notification-btn');
        const notificationsDropdown = document.querySelector('.notifications-dropdown');
        const userDropdownBtn = document.querySelector('.user-dropdown-btn');
        const userDropdown = document.querySelector('.user-dropdown');
        
        // Notification dropdown
        if (notificationBtn && notificationsDropdown) {
            notificationBtn.addEventListener('click', (event) => {
                event.stopPropagation();
                this.toggleDropdown(notificationsDropdown);
                this.closeDropdown(userDropdown);
            });
        }
        
        // User dropdown
        if (userDropdownBtn && userDropdown) {
            userDropdownBtn.addEventListener('click', (event) => {
                event.stopPropagation();
                this.toggleDropdown(userDropdown);
                this.closeDropdown(notificationsDropdown);
            });
        }
        
        this.initializeGenericDropdowns();
        
        // Close dropdowns when clicking outside
        document.addEventListener('click', (event) => {
            if (notificationsDropdown && !notificationBtn?.contains(event.target) && 
                !notificationsDropdown.contains(event.target)) {
                this.closeDropdown(notificationsDropdown);
            }
            
            if (userDropdown && !userDropdownBtn?.contains(event.target) && 
                !userDropdown.contains(event.target)) {
                this.closeDropdown(userDropdown);
            }
            
            // Close all generic dropdowns when clicking outside
            if (!event.target.closest('.dropdown')) {
                document.querySelectorAll('.dropdown-menu.show').forEach(menu => {
                    menu.classList.remove('show');
                });
            }
        });
    }

    initializeGenericDropdowns() {
        document.querySelectorAll('.dropdown-toggle').forEach(toggle => {
            toggle.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                
                // Close all other dropdowns first
                document.querySelectorAll('.dropdown-menu.show').forEach(menu => {
                    if (menu !== toggle.nextElementSibling) {
                        menu.classList.remove('show');
                    }
                });
                
                // Toggle current dropdown
                const menu = toggle.nextElementSibling;
                if (menu && menu.classList.contains('dropdown-menu')) {
                    menu.classList.toggle('show');
                }
            });
        });
        
        // Handle dropdown item clicks
        document.querySelectorAll('.dropdown-item').forEach(item => {
            if (item.tagName.toLowerCase() === 'button') {
                item.addEventListener('click', (e) => {
                    e.stopPropagation();
                    // Close the dropdown after clicking
                    const dropdown = item.closest('.dropdown');
                    if (dropdown) {
                        const menu = dropdown.querySelector('.dropdown-menu');
                        if (menu) {
                            menu.classList.remove('show');
                        }
                    }
                });
            }
        });
    }

    toggleDropdown(dropdown) {
        if (dropdown) {
            dropdown.classList.toggle('active');
        }
    }

    closeDropdown(dropdown) {
        if (dropdown) {
            dropdown.classList.remove('active');
        }
    }
    
    initializePluginManagement() {
        const hasPluginElements = document.querySelector('.plugins-grid') || 
                                 document.querySelector('.plugin-card') ||
                                 document.querySelector('.plugin-select');

        if (!hasPluginElements) {
            console.log('No plugin management elements found, skipping initialization');
            return;
        }

        console.log('Initializing Plugin Management');
        
        this.initializePluginSelection();
        this.initializePluginActions();
        this.initializePluginModals();
    }

    initializePluginSelection() {
        const pluginSelects = document.querySelectorAll('.plugin-select');
        const bulkActions = document.querySelector('.plugin-bulk-actions');
        const selectedCount = document.querySelector('.selected-count');
        const mainActions = document.querySelector('.plugin-main-actions');
        
        if (!pluginSelects.length) return;
        
        // Handle plugin selection changes
        const updateBulkActions = () => {
            const selected = document.querySelectorAll('.plugin-select:checked');
            
            if (selected.length > 0) {
                if (bulkActions) bulkActions.style.display = 'flex';
                if (mainActions) mainActions.style.display = 'none';
                if (selectedCount) {
                    selectedCount.textContent = `${selected.length} plugin${selected.length > 1 ? 's' : ''} selected`;
                }
            } else {
                if (bulkActions) bulkActions.style.display = 'none';
                if (mainActions) mainActions.style.display = 'flex';
            }
        };
        
        pluginSelects.forEach(checkbox => {
            checkbox.addEventListener('change', updateBulkActions);
        });
        
        // Bulk action handlers
        const bulkActivate = document.querySelector('.bulk-activate');
        const bulkDeactivate = document.querySelector('.bulk-deactivate');
        const bulkUninstall = document.querySelector('.bulk-uninstall');
        
        if (bulkActivate) {
            bulkActivate.addEventListener('click', () => this.performBulkAction('activate'));
        }
        
        if (bulkDeactivate) {
            bulkDeactivate.addEventListener('click', () => this.performBulkAction('deactivate'));
        }
        
        if (bulkUninstall) {
            bulkUninstall.addEventListener('click', () => {
                if (confirm('Are you sure you want to uninstall the selected plugins? This action cannot be undone.')) {
                    this.performBulkAction('uninstall');
                }
            });
        }
    }

    initializePluginActions() {
        // Check for updates button
        const checkUpdatesBtn = document.querySelector('.check-updates');
        if (checkUpdatesBtn) {
            checkUpdatesBtn.addEventListener('click', this.checkForUpdates.bind(this));
        }
        
        // Individual plugin update buttons
        document.querySelectorAll('.update-plugin').forEach(btn => {
            btn.addEventListener('click', this.updatePlugin.bind(this));
        });
        
        // Plugin uninstall buttons
        document.querySelectorAll('.uninstall-plugin').forEach(btn => {
            btn.addEventListener('click', this.showUninstallModal.bind(this));
        });
        
        // Download sample plugin
        const downloadSampleBtn = document.getElementById('downloadSampleBtn');
        if (downloadSampleBtn) {
            downloadSampleBtn.addEventListener('click', (e) => {
                e.preventDefault();
                this.showNotification('Sample plugin download will be available soon.', 'info');
            });
        }
    }

    initializePluginModals() {
        const uninstallModal = document.getElementById('uninstallModal');
        const successModal = document.getElementById('successModal');
        const importModal = document.getElementById('importConfigModal');
        
        // Modal close handlers
        document.querySelectorAll('.close-btn, .close-modal').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const modal = e.target.closest('.modal-backdrop');
                if (modal) {
                    modal.classList.remove('active');
                }
            });
        });
        
        // Close modals when clicking backdrop
        [uninstallModal, successModal, importModal].forEach(modal => {
            if (modal) {
                modal.addEventListener('click', (e) => {
                    if (e.target === modal) {
                        modal.classList.remove('active');
                    }
                });
            }
        });
        
        // Uninstall confirmation
        const confirmUninstallBtn = document.getElementById('confirmUninstallBtn');
        if (confirmUninstallBtn) {
            confirmUninstallBtn.addEventListener('click', this.confirmPluginUninstall.bind(this));
        }
        
        // Import config handlers
        const importConfigBtn = document.getElementById('importConfigBtn');
        const confirmImportBtn = document.getElementById('confirmImportBtn');
        
        if (importConfigBtn && importModal) {
            importConfigBtn.addEventListener('click', () => {
                importModal.classList.add('active');
            });
        }
        
        if (confirmImportBtn) {
            confirmImportBtn.addEventListener('click', this.importPluginConfig.bind(this));
        }
    }

    performBulkAction(action) {
        const selected = Array.from(document.querySelectorAll('.plugin-select:checked')).map(cb => cb.value);
        
        if (selected.length === 0) return;
        
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;
        
        fetch('/admin/plugins/bulk-action', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken
            },
            body: JSON.stringify({
                action: action,
                plugins: selected
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                this.showNotification(data.message, 'success');
                setTimeout(() => location.reload(), 1500);
            } else {
                this.showNotification(data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Bulk action error:', error);
            this.showNotification('An error occurred while performing the bulk action.', 'error');
        });
    }

    checkForUpdates() {
        const btn = document.querySelector('.check-updates');
        if (!btn) return;
        
        const originalText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Checking...';
        btn.disabled = true;
        
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;
        
        fetch('/admin/plugins/updates/check', {
            headers: {
                'X-CSRF-TOKEN': csrfToken
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                this.showNotification(`Found ${data.updates.length} update(s) available.`, 'success');
                if (data.updates.length > 0) {
                    setTimeout(() => location.reload(), 1500);
                }
            } else {
                this.showNotification(data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Update check error:', error);
            this.showNotification('An error occurred while checking for updates.', 'error');
        })
        .finally(() => {
            btn.innerHTML = originalText;
            btn.disabled = false;
        });
    }

    updatePlugin(e) {
        const plugin = e.target.dataset.plugin;
        const btn = e.target;
        const originalText = btn.innerHTML;
        
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';
        btn.disabled = true;
        
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;
        
        fetch(`/admin/plugins/${plugin}/update`, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': csrfToken
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                this.showNotification(data.message, 'success');
                setTimeout(() => location.reload(), 1500);
            } else {
                this.showNotification(data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Update error:', error);
            this.showNotification('An error occurred while updating the plugin.', 'error');
        })
        .finally(() => {
            btn.innerHTML = originalText;
            btn.disabled = false;
        });
    }

    showUninstallModal(e) {
        const plugin = e.target.dataset.plugin;
        const uninstallModal = document.getElementById('uninstallModal');
        const uninstallPluginName = document.getElementById('uninstallPluginName');
        
        if (uninstallModal && uninstallPluginName) {
            this.currentUninstallPlugin = plugin;
            uninstallPluginName.textContent = plugin;
            uninstallModal.classList.add('active');
        }
    }

    confirmPluginUninstall() {
        if (!this.currentUninstallPlugin) return;
        
        const btn = document.getElementById('confirmUninstallBtn');
        const originalText = btn?.textContent;
        
        if (btn) {
            btn.textContent = 'Uninstalling...';
            btn.disabled = true;
        }
        
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;
        
        fetch(`/admin/plugins/${this.currentUninstallPlugin}`, {
            method: 'DELETE',
            headers: {
                'X-CSRF-TOKEN': csrfToken
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                this.showNotification(data.message, 'success');
                setTimeout(() => location.reload(), 1500);
            } else {
                this.showNotification(data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Uninstall error:', error);
            this.showNotification('An error occurred while uninstalling the plugin.', 'error');
        })
        .finally(() => {
            const uninstallModal = document.getElementById('uninstallModal');
            if (uninstallModal) uninstallModal.classList.remove('active');
            
            if (btn) {
                btn.textContent = originalText;
                btn.disabled = false;
            }
            
            this.currentUninstallPlugin = null;
        });
    }

    importPluginConfig() {
        const formData = new FormData(document.getElementById('importConfigForm'));
        const fileInput = document.getElementById('configFile');
        
        if (!fileInput?.files.length) {
            this.showNotification('Please select a configuration file.', 'error');
            return;
        }
        
        const btn = document.getElementById('confirmImportBtn');
        const originalText = btn?.textContent;
        
        if (btn) {
            btn.textContent = 'Importing...';
            btn.disabled = true;
        }
        
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;
        const pluginName = window.location.pathname.split('/').pop();
        
        fetch(`/admin/plugins/${pluginName}/config/import`, {
            method: 'POST',
            body: formData,
            headers: {
                'X-CSRF-TOKEN': csrfToken
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                this.showNotification(data.message, 'success');
                setTimeout(() => location.reload(), 2000);
            } else {
                this.showNotification(data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Import error:', error);
            this.showNotification('An error occurred while importing configuration.', 'error');
        })
        .finally(() => {
            const importModal = document.getElementById('importConfigModal');
            if (importModal) importModal.classList.remove('active');
            
            if (btn) {
                btn.textContent = originalText;
                btn.disabled = false;
            }
        });
    }
    
    initializeTabNavigation() {
        const tabLinks = document.querySelectorAll('.nav-tabs .nav-link');
        
        tabLinks.forEach(tabLink => {
            tabLink.addEventListener('click', (e) => {
                const isActive = tabLink.classList.contains('active');
                const href = tabLink.getAttribute('href');
                
                // Prevent default if it's a hash link or empty
                if (!href || href === '#' || href.startsWith('#')) {
                    e.preventDefault();
                }
                
                // Don't process if already active
                if (isActive) return;
                
                // Remove active class from all tabs in the same group
                const tabGroup = tabLink.closest('.nav-tabs');
                if (tabGroup) {
                    tabGroup.querySelectorAll('.nav-link').forEach(link => {
                        link.classList.remove('active');
                    });
                }
                
                // Add active class to clicked tab
                tabLink.classList.add('active');
                
                // Handle tab panes
                const target = tabLink.dataset.target || tabLink.getAttribute('href');
                if (target && target.startsWith('#')) {
                    const paneId = target.substring(1);
                    this.switchTabPane(paneId);
                }
            });
        });
    }

    switchTabPane(targetId) {
        // Hide all tab panes
        document.querySelectorAll('.tab-pane').forEach(pane => {
            pane.classList.remove('active', 'show');
        });
        
        // Show target pane
        const targetPane = document.getElementById(targetId);
        if (targetPane) {
            targetPane.classList.add('active', 'show');
        }
    }
    
    initializeFormHandlers() {
        this.initializeJsonValidation();
        this.initializeTextareaAutoResize();
        this.initializeFormValidation();
        this.initializePluginConfigForms();
    }

    initializePluginConfigForms() {
        // Configuration form submission
        const configForm = document.getElementById('configForm');
        if (configForm) {
            configForm.addEventListener('submit', (e) => {
                e.preventDefault();
                
                const formData = new FormData(configForm);
                const submitBtn = configForm.querySelector('button[type="submit"]');
                const originalText = submitBtn?.innerHTML;
                
                if (submitBtn) {
                    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';
                    submitBtn.disabled = true;
                }
                
                const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;
                
                fetch(configForm.action, {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-CSRF-TOKEN': csrfToken
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        this.showNotification(data.message || 'Configuration saved successfully!', 'success');
                    } else {
                        this.showNotification(data.message || 'Failed to save configuration.', 'error');
                    }
                })
                .catch(error => {
                    console.error('Config save error:', error);
                    this.showNotification('An error occurred while saving configuration.', 'error');
                })
                .finally(() => {
                    if (submitBtn) {
                        submitBtn.innerHTML = originalText;
                        submitBtn.disabled = false;
                    }
                });
            });
        }
        
        // JSON format buttons
        document.querySelectorAll('.format-json-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const targetId = e.target.dataset.target;
                const textarea = document.getElementById(targetId);
                
                if (textarea) {
                    try {
                        const parsed = JSON.parse(textarea.value);
                        textarea.value = JSON.stringify(parsed, null, 2);
                        this.showNotification('JSON formatted successfully!', 'success');
                    } catch (error) {
                        this.showNotification('Invalid JSON format!', 'error');
                    }
                }
            });
        });
        
        // Reset configuration button
        const resetConfigBtn = document.getElementById('resetConfigBtn');
        if (resetConfigBtn) {
            resetConfigBtn.addEventListener('click', () => {
                if (confirm('Are you sure you want to reset all configuration to default values?')) {
                    const form = document.getElementById('configForm');
                    if (form) {
                        const inputs = form.querySelectorAll('input, select, textarea');
                        
                        inputs.forEach(input => {
                            const defaultValue = input.getAttribute('data-default') || '';
                            
                            if (input.type === 'checkbox') {
                                input.checked = defaultValue === 'true' || defaultValue === '1';
                            } else {
                                input.value = defaultValue;
                            }
                        });
                        
                        this.showNotification('Configuration reset to default values. Don\'t forget to save!', 'info');
                    }
                }
            });
        }
        
        // Color picker synchronization
        document.querySelectorAll('.color-picker-wrapper').forEach(wrapper => {
            const colorInput = wrapper.querySelector('.color-picker-input');
            const textInput = wrapper.querySelector('.color-text-input');
            
            if (colorInput && textInput) {
                colorInput.addEventListener('input', () => {
                    textInput.value = colorInput.value;
                });
                
                textInput.addEventListener('input', () => {
                    if (/^#[0-9A-F]{6}$/i.test(textInput.value)) {
                        colorInput.value = textInput.value;
                    }
                });
            }
        });
    }

    initializeJsonValidation() {
        // Handle JSON configuration fields
        const jsonTextareas = document.querySelectorAll('textarea[data-type="json"], textarea[name*="json"]');
        
        jsonTextareas.forEach(textarea => {
            try {
                // Try to format existing JSON for better readability
                const value = textarea.value.trim();
                if (value) {
                    const jsonValue = JSON.parse(value);
                    textarea.value = JSON.stringify(jsonValue, null, 2);
                }
            } catch (e) {
                console.log('Could not parse existing JSON value:', e);
            }
            
            // Add validation on blur
            textarea.addEventListener('blur', () => {
                this.validateJsonField(textarea);
            });
        });
    }

    validateJsonField(textarea) {
        const value = textarea.value.trim();
        if (!value) return true;
        
        try {
            JSON.parse(value);
            textarea.classList.remove('is-invalid');
            this.removeFieldError(textarea);
            return true;
        } catch (e) {
            textarea.classList.add('is-invalid');
            this.showFieldError(textarea, 'Invalid JSON format: ' + e.message);
            return false;
        }
    }

    showFieldError(field, message) {
        // Remove existing error
        this.removeFieldError(field);
        
        // Create error element
        const errorElement = document.createElement('div');
        errorElement.className = 'error-message';
        errorElement.textContent = message;
        
        // Insert after field
        field.parentNode.insertBefore(errorElement, field.nextSibling);
        
        // Add error class to form group
        const formGroup = field.closest('.form-group');
        if (formGroup) {
            formGroup.classList.add('has-error');
        }
    }

    removeFieldError(field) {
        const errorElement = field.parentNode.querySelector('.error-message');
        if (errorElement) {
            errorElement.remove();
        }
        
        const formGroup = field.closest('.form-group');
        if (formGroup) {
            formGroup.classList.remove('has-error');
        }
    }

    initializeTextareaAutoResize() {
        const textareas = document.querySelectorAll('textarea');
        
        textareas.forEach(textarea => {
            // Set initial height
            this.resizeTextarea(textarea);
            
            // Resize on input
            textarea.addEventListener('input', () => {
                this.resizeTextarea(textarea);
            });
            
            // Enhanced editing experience
            textarea.addEventListener('focus', () => {
                const currentHeight = textarea.style.height || textarea.scrollHeight + 'px';
                const minHeight = Math.max(120, textarea.scrollHeight);
                
                textarea.style.transition = 'height 0.2s ease';
                textarea.style.height = minHeight + 'px';
                
                setTimeout(() => {
                    textarea.style.transition = '';
                }, 200);
            });
            
            textarea.addEventListener('blur', () => {
                textarea.style.transition = 'height 0.2s ease';
                this.resizeTextarea(textarea);
                
                setTimeout(() => {
                    textarea.style.transition = '';
                }, 200);
            });
        });
    }

    resizeTextarea(textarea) {
        textarea.style.height = 'auto';
        textarea.style.height = Math.max(textarea.scrollHeight, 60) + 'px';
    }

    initializeFormValidation() {
        const forms = document.querySelectorAll('form');
        
        forms.forEach(form => {
            form.addEventListener('submit', (e) => {
                if (!this.validateForm(form)) {
                    e.preventDefault();
                    return false;
                }
            });
        });
    }

    validateForm(form) {
        let isValid = true;
        
        // Validate JSON fields
        const jsonFields = form.querySelectorAll('textarea[data-type="json"], textarea[name*="json"]');
        jsonFields.forEach(field => {
            if (!this.validateJsonField(field)) {
                isValid = false;
            }
        });
        
        // Validate required fields
        const requiredFields = form.querySelectorAll('[required]');
        requiredFields.forEach(field => {
            if (!field.value.trim()) {
                this.showFieldError(field, 'This field is required');
                isValid = false;
            }
        });
        
        return isValid;
    }
    
    initializeSpecialInputs() {
        // Handle file uploads with previews
        const fileInputs = document.querySelectorAll('input[type="file"]');
        fileInputs.forEach(input => {
            input.addEventListener('change', (e) => {
                this.handleFileUpload(e.target);
            });
        });
    }

    handleFileUpload(input) {
        const files = input.files;
        if (!files || files.length === 0) return;
        
        const previewContainer = input.closest('.file-upload-wrapper')?.querySelector('.file-upload-preview');
        if (!previewContainer) return;
        
        // Clear existing previews
        previewContainer.innerHTML = '';
        
        Array.from(files).forEach(file => {
            const reader = new FileReader();
            reader.onload = (e) => {
                const preview = this.createFilePreview(file, e.target.result);
                previewContainer.appendChild(preview);
            };
            reader.readAsDataURL(file);
        });
    }

    createFilePreview(file, src) {
        const preview = document.createElement('div');
        preview.className = 'new-file';
        
        const fileName = document.createElement('span');
        fileName.className = 'file-name';
        fileName.textContent = file.name;
        
        if (file.type.startsWith('image/')) {
            const img = document.createElement('img');
            img.className = 'file-preview';
            img.src = src;
            img.alt = file.name;
            preview.appendChild(fileName);
            preview.appendChild(img);
        } else {
            const icon = document.createElement('i');
            icon.className = 'fas fa-file';
            preview.appendChild(fileName);
            preview.appendChild(icon);
        }
        
        return preview;
    }
    
    initializeColorPickers() {
        const colorPickers = document.querySelectorAll('.color-picker-input');
        
        colorPickers.forEach(picker => {
            const wrapper = picker.closest('.color-picker-wrapper');
            const textInput = wrapper?.querySelector('.color-text-input');
            
            if (!textInput) return;
            
            // Update text when color is changed
            picker.addEventListener('input', () => {
                textInput.value = picker.value.toUpperCase();
                this.validateColorInput(textInput);
            });
            
            // Update color when text is changed
            textInput.addEventListener('input', () => {
                const value = this.normalizeColorValue(textInput.value);
                textInput.value = value;
                
                if (this.isValidColor(value)) {
                    picker.value = value;
                }
            });
            
            // Format on blur
            textInput.addEventListener('blur', () => {
                const value = this.formatColorValue(textInput.value);
                textInput.value = value;
                picker.value = value;
                this.validateColorInput(textInput);
            });
            
            // Initial validation
            this.validateColorInput(textInput);
        });
    }

    normalizeColorValue(value) {
        if (!value) return '';
        
        // Remove non-hex characters
        value = value.replace(/[^#0-9A-Fa-f]/g, '');
        
        // Add # if missing
        if (value && !value.startsWith('#')) {
            value = '#' + value;
        }
        
        return value.toUpperCase();
    }

    formatColorValue(value) {
        value = this.normalizeColorValue(value);
        
        if (!value) return '#000000';
        
        // Ensure we have at least 4 chars (#RGB)
        if (value.length < 4) {
            return '#000000';
        }
        
        // Convert short form to long form (#RGB to #RRGGBB)
        if (value.length === 4) {
            const r = value[1];
            const g = value[2];
            const b = value[3];
            value = `#${r}${r}${g}${g}${b}${b}`;
        }
        
        // Truncate if too long
        if (value.length > 7) {
            value = value.substring(0, 7);
        }
        
        // Pad with zeros if needed
        while (value.length < 7) {
            value += '0';
        }
        
        return value;
    }

    isValidColor(value) {
        return /^#([0-9A-F]{3}){1,2}$/i.test(value);
    }

    validateColorInput(input) {
        const value = input.value;
        const isValid = !value || this.isValidColor(value);
        
        input.classList.toggle('is-invalid', !isValid);
        
        if (!isValid) {
            this.showFieldError(input, 'Please enter a valid hex color (e.g., #FF0000)');
        } else {
            this.removeFieldError(input);
        }
        
        return isValid;
    }

    initializeIconPickers() {
        const iconPickers = document.querySelectorAll('.icon-picker-wrapper');
        
        iconPickers.forEach(wrapper => {
            const input = wrapper.querySelector('.icon-picker-input');
            const preview = wrapper.querySelector('.icon-picker-preview i');
            const dropdown = wrapper.querySelector('.icon-picker-dropdown');
            const searchInput = wrapper.querySelector('input[type="search"]');
            const iconList = wrapper.querySelector('.icon-picker-list');
            
            if (!input || !preview || !dropdown || !iconList) return;
            
            // Initialize icon list
            this.populateIconList(iconList, this.getFontAwesomeIcons(), input.value);
            
            // Update preview on input change
            input.addEventListener('input', () => {
                this.updateIconPreview(preview, input.value);
            });
            
            // Show dropdown on focus
            input.addEventListener('focus', () => {
                dropdown.classList.add('active');
            });
            
            // Filter icons on search
            if (searchInput) {
                searchInput.addEventListener('input', () => {
                    const searchTerm = searchInput.value.toLowerCase();
                    const filteredIcons = this.getFontAwesomeIcons().filter(icon => 
                        icon.toLowerCase().includes(searchTerm)
                    );
                    this.populateIconList(iconList, filteredIcons, input.value);
                });
            }
            
            // Handle icon selection
            iconList.addEventListener('click', (e) => {
                const iconItem = e.target.closest('.icon-item');
                if (iconItem) {
                    const selectedIcon = iconItem.dataset.icon;
                    input.value = selectedIcon;
                    this.updateIconPreview(preview, selectedIcon);
                    
                    // Update active state
                    iconList.querySelectorAll('.icon-item').forEach(item => {
                        item.classList.remove('active');
                    });
                    iconItem.classList.add('active');
                    
                    // Close dropdown
                    dropdown.classList.remove('active');
                }
            });
            
            // Close dropdown when clicking outside
            document.addEventListener('click', (e) => {
                if (!wrapper.contains(e.target)) {
                    dropdown.classList.remove('active');
                }
            });
        });
    }

    updateIconPreview(preview, iconName) {
        if (preview && iconName) {
            preview.className = `fas fa-${iconName}`;
        }
    }

    populateIconList(container, icons, selectedIcon) {
        container.innerHTML = '';
        
        if (icons.length === 0) {
            const noResults = document.createElement('div');
            noResults.className = 'no-results';
            noResults.textContent = 'No matching icons found';
            container.appendChild(noResults);
            return;
        }
        
        icons.forEach(icon => {
            const iconItem = document.createElement('div');
            iconItem.className = `icon-item${icon === selectedIcon ? ' active' : ''}`;
            iconItem.dataset.icon = icon;
            iconItem.innerHTML = `<i class="fas fa-${icon}"></i>`;
            iconItem.title = icon;
            
            container.appendChild(iconItem);
        });
    }

    getFontAwesomeIcons() {
        return [
            // User & People
            'user', 'users', 'user-plus', 'user-minus', 'user-check', 'user-times',
            'user-cog', 'user-edit', 'user-friends', 'user-graduate', 'user-md',
            'user-nurse', 'user-tie', 'user-secret', 'user-astronaut', 'user-ninja',
            'id-card', 'id-badge', 'address-card', 'portrait',
            
            // Interface & Navigation
            'home', 'dashboard', 'menu', 'bars', 'ellipsis-h', 'ellipsis-v',
            'cog', 'settings', 'gear', 'sliders-h', 'adjust', 'toggle-on', 'toggle-off',
            'power-off', 'sign-in-alt', 'sign-out-alt', 'door-open', 'door-closed',
            
            // Actions & Controls
            'edit', 'pencil-alt', 'pen', 'marker', 'highlighter', 'eraser',
            'save', 'copy', 'cut', 'paste', 'clone', 'share', 'share-alt',
            'trash', 'delete', 'recycle', 'undo', 'redo', 'refresh', 'sync',
            'plus', 'minus', 'plus-circle', 'minus-circle', 'plus-square', 'minus-square',
            'check', 'check-circle', 'check-square', 'times', 'times-circle', 'ban',
            'exclamation', 'exclamation-circle', 'exclamation-triangle', 'question',
            'question-circle', 'info', 'info-circle',
            
            // Search & Filter
            'search', 'search-plus', 'search-minus', 'filter', 'sort', 'sort-up',
            'sort-down', 'sort-alpha-up', 'sort-alpha-down', 'sort-numeric-up',
            'sort-numeric-down', 'sort-amount-up', 'sort-amount-down',
            
            // Plugin & Extension specific
            'puzzle-piece', 'plug', 'download', 'upload', 'cloud-download-alt',
            'cloud-upload-alt', 'archive', 'box', 'package', 'cubes', 'layer-group'
        ];
    }
    
    initializeCodeEditors() {
        const codeTextareas = document.querySelectorAll('.code-editor, textarea[data-type="code"]');
        
        codeTextareas.forEach(textarea => {
            const mode = textarea.dataset.mode || this.detectCodeMode(textarea);
            
            if (typeof CodeMirror !== 'undefined') {
                const editor = CodeMirror.fromTextArea(textarea, {
                    lineNumbers: true,
                    mode: mode,
                    theme: 'darcula',
                    autoCloseBrackets: true,
                    matchBrackets: true,
                    indentUnit: 2,
                    tabSize: 2,
                    lineWrapping: true
                });
                
                // Store reference for later use
                textarea._codeMirror = editor;
            }
        });
    }

    detectCodeMode(textarea) {
        const name = textarea.name || textarea.id || '';
        
        if (name.includes('css') || textarea.classList.contains('css')) return 'css';
        if (name.includes('js') || name.includes('javascript') || textarea.classList.contains('javascript')) return 'javascript';
        if (name.includes('html') || textarea.classList.contains('html')) return 'htmlmixed';
        if (name.includes('json') || textarea.classList.contains('json')) return 'application/json';
        if (name.includes('php') || textarea.classList.contains('php')) return 'php';
        if (name.includes('sql') || textarea.classList.contains('sql')) return 'sql';
        
        return 'text/plain';
    }
    
    initializeAlerts() {
        const alerts = document.querySelectorAll('.alert:not(.alert-permanent)');
        
        alerts.forEach(alert => {
            // Add close button if not present and alert is dismissible
            if (alert.classList.contains('alert-dismissible') && !alert.querySelector('.alert-close')) {
                const closeBtn = document.createElement('button');
                closeBtn.className = 'alert-close';
                closeBtn.innerHTML = '<i class="fas fa-times"></i>';
                closeBtn.addEventListener('click', () => this.closeAlert(alert));
                alert.appendChild(closeBtn);
            }
            
            // Auto-dismiss after 5 seconds (except permanent alerts)
            if (!alert.classList.contains('alert-permanent')) {
                setTimeout(() => {
                    this.closeAlert(alert);
                }, 5000);
            }
        });
        
        // Handle existing close buttons
        document.querySelectorAll('.alert-close').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const alert = e.target.closest('.alert');
                if (alert) {
                    this.closeAlert(alert);
                }
            });
        });
    }

    closeAlert(alert) {
        alert.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
        alert.style.opacity = '0';
        alert.style.transform = 'translateY(-100%)';
        
        setTimeout(() => {
            if (alert.parentNode) {
                alert.parentNode.removeChild(alert);
            }
        }, 300);
    }
    
    showNotification(message, type = 'info', duration = 5000) {
        const notification = document.createElement('div');
        notification.className = `alert alert-${type} alert-dismissible`;
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            max-width: 300px;
            opacity: 0;
            transform: translateY(-20px);
            transition: all 0.3s ease;
            padding: 1rem 3rem 1rem 1rem;
        `;
        
        notification.innerHTML = `
            <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
            ${message}
            <button type="button" class="alert-close" onclick="this.parentElement.remove()">
                <i class="fas fa-times"></i>
            </button>
        `;
        
        document.body.appendChild(notification);
        
        // Trigger animation
        requestAnimationFrame(() => {
            notification.style.opacity = '1';
            notification.style.transform = 'translateY(0)';
        });
        
        // Auto remove
        setTimeout(() => {
            this.closeAlert(notification);
        }, duration);
        
        return notification;
    }

    // Debounce utility
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // Throttle utility
    throttle(func, limit) {
        let inThrottle;
        return function(...args) {
            if (!inThrottle) {
                func.apply(this, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }
}

// Initialize the admin panel when the script loads
const adminPanel = new AdminPanel();

// Make it globally accessible for debugging
window.adminPanel = adminPanel;