/**
 * ===============================================
 * ADMIN PANEL JAVASCRIPT - WebTopup
 * Modern admin panel interactions
 * ===============================================
 */

document.addEventListener('DOMContentLoaded', function() {
    // Initialize all components
    initSidebarToggle();
    initDeleteConfirmation();
    initFileUpload();
    initFormValidation();
    initAutoSlug();
    initAlertAutoDismiss();
});

/**
 * Sidebar Toggle for Mobile
 * Handles hamburger menu and sidebar visibility on mobile devices
 */
function initSidebarToggle() {
    const sidebarToggle = document.querySelector('[data-sidebar-toggle]');
    const sidebar = document.querySelector('.admin-sidebar');
    
    console.log('Sidebar Toggle Init:', {
        button: sidebarToggle,
        sidebar: sidebar
    });
    
    if (!sidebarToggle || !sidebar) {
        console.warn('Sidebar toggle or sidebar not found!');
        return;
    }
    
    let isToggling = false;
    
    // Toggle sidebar open/close
    sidebarToggle.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        if (isToggling) return;
        isToggling = true;
        
        console.log('Sidebar toggle clicked');
        const isOpen = sidebar.classList.contains('open');
        
        if (isOpen) {
            closeSidebar();
        } else {
            sidebar.classList.add('open');
            console.log('Sidebar opened');
            
            // Add outside click handler after a delay to prevent immediate closing
            setTimeout(() => {
                document.addEventListener('click', handleOutsideClick);
                isToggling = false;
            }, 100);
        }
        
        if (!isOpen) {
            setTimeout(() => {
                isToggling = false;
            }, 100);
        }
    });
    
    // Close sidebar when clicking outside on mobile
    function handleOutsideClick(e) {
        console.log('Outside click detected');
        if (!sidebar.contains(e.target) && !sidebarToggle.contains(e.target)) {
            console.log('Closing sidebar');
            closeSidebar();
        }
    }
    
    // Close sidebar helper
    function closeSidebar() {
        sidebar.classList.remove('open');
        document.removeEventListener('click', handleOutsideClick);
        console.log('Sidebar closed');
    }
    
    // Close sidebar when clicking navigation links on mobile
    const navLinks = sidebar.querySelectorAll('.nav-link');
    navLinks.forEach(link => {
        link.addEventListener('click', function() {
            if (window.innerWidth <= 768) {
                closeSidebar();
            }
        });
    });
    
    // Handle window resize
    window.addEventListener('resize', function() {
        if (window.innerWidth > 768) {
            closeSidebar();
        }
    });
}

/**
 * Delete Confirmation
 * Shows confirmation dialog before deleting items
 */
function initDeleteConfirmation() {
    const deleteForms = document.querySelectorAll('.delete-form');
    
    deleteForms.forEach(form => {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const itemName = this.getAttribute('data-item-name') || 'this item';
            const confirmMessage = `Are you sure you want to delete "${itemName}"?\n\nThis action cannot be undone.`;
            
            if (confirm(confirmMessage)) {
                this.submit();
            }
        });
    });

    // Also handle delete buttons with data-confirm
    const deleteButtons = document.querySelectorAll('[data-confirm]');
    
    deleteButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            const confirmMessage = this.getAttribute('data-confirm');
            
            if (!confirm(confirmMessage)) {
                e.preventDefault();
                return false;
            }
        });
    });
}

/**
 * File Upload Preview
 * Shows preview of uploaded images
 */
function initFileUpload() {
    const fileInputs = document.querySelectorAll('.form-file');
    
    fileInputs.forEach(input => {
        input.addEventListener('change', function(e) {
            const file = e.target.files[0];
            
            if (file && file.type.startsWith('image/')) {
                const reader = new FileReader();
                
                reader.onload = function(event) {
                    // Find or create preview element
                    let previewContainer = input.parentElement.querySelector('.file-preview');
                    
                    if (!previewContainer) {
                        previewContainer = document.createElement('div');
                        previewContainer.className = 'file-preview';
                        input.parentElement.appendChild(previewContainer);
                    }
                    
                    previewContainer.innerHTML = `
                        <img src="${event.target.result}" alt="Preview" class="file-preview-img">
                        <div>
                            <div style="font-size: 0.95rem; font-weight: 600; color: var(--admin-text-primary);">${file.name}</div>
                            <div style="font-size: 0.875rem; color: var(--admin-text-secondary);">${formatFileSize(file.size)}</div>
                        </div>
                    `;
                };
                
                reader.readAsDataURL(file);
            }
        });
    });

    // Handle file upload area clicks
    const uploadAreas = document.querySelectorAll('.file-upload-area');
    
    uploadAreas.forEach(area => {
        area.addEventListener('click', function() {
            const fileInput = this.parentElement.querySelector('.form-file');
            if (fileInput) {
                fileInput.click();
            }
        });

        // Drag and drop support
        area.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.style.borderColor = 'var(--admin-primary)';
            this.style.background = 'rgba(12, 149, 30, 0.05)';
        });

        area.addEventListener('dragleave', function() {
            this.style.borderColor = '';
            this.style.background = '';
        });

        area.addEventListener('drop', function(e) {
            e.preventDefault();
            this.style.borderColor = '';
            this.style.background = '';
            
            const fileInput = this.parentElement.querySelector('.form-file');
            if (fileInput && e.dataTransfer.files.length > 0) {
                fileInput.files = e.dataTransfer.files;
                
                // Trigger change event
                const event = new Event('change', { bubbles: true });
                fileInput.dispatchEvent(event);
            }
        });
    });
}

/**
 * Form Validation
 * Client-side validation for better UX
 */
function initFormValidation() {
    const forms = document.querySelectorAll('form[data-validate]');
    
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            let isValid = true;
            
            // Clear previous errors
            this.querySelectorAll('.error-message').forEach(msg => msg.remove());
            this.querySelectorAll('.form-input, .form-select, .form-textarea').forEach(input => {
                input.style.borderColor = '';
            });
            
            // Check required fields
            const requiredFields = this.querySelectorAll('[required]');
            
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    isValid = false;
                    showFieldError(field, 'This field is required');
                }
            });
            
            // Check email fields
            const emailFields = this.querySelectorAll('input[type="email"]');
            
            emailFields.forEach(field => {
                if (field.value && !isValidEmail(field.value)) {
                    isValid = false;
                    showFieldError(field, 'Please enter a valid email address');
                }
            });
            
            // Check number fields
            const numberFields = this.querySelectorAll('input[type="number"]');
            
            numberFields.forEach(field => {
                const min = field.getAttribute('min');
                const max = field.getAttribute('max');
                const value = parseFloat(field.value);
                
                if (field.value && isNaN(value)) {
                    isValid = false;
                    showFieldError(field, 'Please enter a valid number');
                } else if (min !== null && value < parseFloat(min)) {
                    isValid = false;
                    showFieldError(field, `Value must be at least ${min}`);
                } else if (max !== null && value > parseFloat(max)) {
                    isValid = false;
                    showFieldError(field, `Value must be at most ${max}`);
                }
            });
            
            if (!isValid) {
                e.preventDefault();
                
                // Scroll to first error
                const firstError = this.querySelector('.error-message');
                if (firstError) {
                    firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }
            }
        });
    });
}

/**
 * Auto Slug Generation
 * Automatically generate slug from name field
 */
function initAutoSlug() {
    const nameFields = document.querySelectorAll('[data-slug-source]');
    
    nameFields.forEach(nameField => {
        const slugField = document.getElementById(nameField.getAttribute('data-slug-source'));
        
        if (slugField) {
            nameField.addEventListener('input', function() {
                if (!slugField.value || slugField.hasAttribute('data-auto-slug')) {
                    const slug = generateSlug(this.value);
                    slugField.value = slug;
                    slugField.setAttribute('data-auto-slug', 'true');
                }
            });
            
            slugField.addEventListener('input', function() {
                if (this.value) {
                    this.removeAttribute('data-auto-slug');
                }
            });
        }
    });
}

/**
 * Auto Dismiss Alerts
 * Automatically dismiss success alerts after 5 seconds
 */
function initAlertAutoDismiss() {
    const successAlerts = document.querySelectorAll('.alert-success');
    
    successAlerts.forEach(alert => {
        setTimeout(() => {
            alert.style.transition = 'opacity 0.5s ease';
            alert.style.opacity = '0';
            
            setTimeout(() => {
                alert.remove();
            }, 500);
        }, 5000);
    });
}

/**
 * Utility Functions
 */

function showFieldError(field, message) {
    field.style.borderColor = 'var(--admin-danger)';
    
    const errorDiv = document.createElement('div');
    errorDiv.className = 'error-message';
    errorDiv.style.cssText = 'color: var(--admin-danger); font-size: 0.875rem; margin-top: 0.25rem;';
    errorDiv.textContent = message;
    
    field.parentElement.appendChild(errorDiv);
}

function isValidEmail(email) {
    const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return regex.test(email);
}

function generateSlug(text) {
    return text
        .toLowerCase()
        .trim()
        .replace(/[^\w\s-]/g, '')
        .replace(/[\s_-]+/g, '-')
        .replace(/^-+|-+$/g, '');
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}

/**
 * Mobile Sidebar Toggle
 */
const sidebarToggle = document.querySelector('[data-sidebar-toggle]');
const sidebar = document.querySelector('.admin-sidebar');

if (sidebarToggle && sidebar) {
    sidebarToggle.addEventListener('click', function() {
        sidebar.classList.toggle('open');
    });

    // Close sidebar when clicking outside on mobile
    document.addEventListener('click', function(e) {
        if (window.innerWidth <= 768) {
            if (!sidebar.contains(e.target) && !sidebarToggle.contains(e.target)) {
                sidebar.classList.remove('open');
            }
        }
    });
}

/**
 * Table Row Actions
 * Handle quick actions on table rows
 */
document.querySelectorAll('.data-table tbody tr').forEach(row => {
    row.addEventListener('contextmenu', function(e) {
        e.preventDefault();
        // Could add context menu here if needed
    });
});

/**
 * Search Filter (if needed)
 */
const searchInputs = document.querySelectorAll('[data-search]');

searchInputs.forEach(input => {
    const targetTable = document.querySelector(input.getAttribute('data-search'));
    
    if (targetTable) {
        input.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            const rows = targetTable.querySelectorAll('tbody tr');
            
            rows.forEach(row => {
                const text = row.textContent.toLowerCase();
                row.style.display = text.includes(searchTerm) ? '' : 'none';
            });
        });
    }
});

/**
 * Sort Table Columns (if needed)
 */
document.querySelectorAll('[data-sortable]').forEach(th => {
    th.style.cursor = 'pointer';
    th.addEventListener('click', function() {
        const table = this.closest('table');
        const tbody = table.querySelector('tbody');
        const rows = Array.from(tbody.querySelectorAll('tr'));
        const columnIndex = Array.from(this.parentElement.children).indexOf(this);
        const currentDirection = this.getAttribute('data-sort-direction') || 'asc';
        const newDirection = currentDirection === 'asc' ? 'desc' : 'asc';
        
        rows.sort((a, b) => {
            const aValue = a.children[columnIndex].textContent.trim();
            const bValue = b.children[columnIndex].textContent.trim();
            
            if (newDirection === 'asc') {
                return aValue.localeCompare(bValue, undefined, { numeric: true });
            } else {
                return bValue.localeCompare(aValue, undefined, { numeric: true });
            }
        });
        
        rows.forEach(row => tbody.appendChild(row));
        
        // Update sort direction
        table.querySelectorAll('[data-sortable]').forEach(header => {
            header.removeAttribute('data-sort-direction');
        });
        this.setAttribute('data-sort-direction', newDirection);
    });
});
