// Admin Panel JavaScript
document.addEventListener('DOMContentLoaded', function() {
    // Initialize Summernote editor
    if (typeof $ !== 'undefined' && $.fn.summernote) {
        $('#content').summernote({
            height: 400,
            placeholder: 'Write your post content here...',
            toolbar: [
                ['style', ['style']],
                ['font', ['bold', 'underline', 'clear']],
                ['color', ['color']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['table', ['table']],
                ['insert', ['link', 'picture', 'video']],
                ['view', ['fullscreen', 'codeview', 'help']]
            ],
            callbacks: {
                onImageUpload: function(files) {
                    // Handle image upload if needed
                    console.log('Image upload:', files);
                }
            }
        });
    }
    
    // Form validation
    const postForm = document.querySelector('.post-form');
    
    if (postForm) {
        postForm.addEventListener('submit', function(e) {
            const title = document.getElementById('title').value.trim();
            const content = $('#content').summernote('code') || document.getElementById('content').value;
            
            if (!title) {
                e.preventDefault();
                alert('Please enter a post title.');
                document.getElementById('title').focus();
                return false;
            }
            
            if (!content || content === '<p><br></p>') {
                e.preventDefault();
                alert('Please enter post content.');
                $('#content').summernote('focus');
                return false;
            }
        });
    }
    
    // Auto-save draft functionality (optional enhancement)
    let autoSaveTimer;
    const autoSaveInterval = 30000; // 30 seconds
    
    function autoSave() {
        const form = document.querySelector('.post-form');
        if (!form) return;
        
        const formData = new FormData(form);
        formData.append('auto_save', '1');
        
        // This would require additional PHP endpoint for auto-save
        console.log('Auto-save would trigger here');
    }
    
    // Start auto-save timer when editing content
    if (document.getElementById('content')) {
        $('#content').on('summernote.change', function() {
            clearTimeout(autoSaveTimer);
            autoSaveTimer = setTimeout(autoSave, autoSaveInterval);
        });
    }
    
    // Confirm delete actions
    const deleteLinks = document.querySelectorAll('a[href*="action=delete"]');
    
    deleteLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            if (!confirm('Are you sure you want to delete this item? This action cannot be undone.')) {
                e.preventDefault();
            }
        });
    });
    
    // Table row click to edit
    const tableRows = document.querySelectorAll('.posts-table tbody tr');
    
    tableRows.forEach(row => {
        row.addEventListener('click', function(e) {
            // Don't trigger on button clicks
            if (e.target.tagName === 'A' || e.target.tagName === 'BUTTON') {
                return;
            }
            
            const editLink = row.querySelector('a[href*="edit_post.php"]');
            if (editLink) {
                window.location.href = editLink.href;
            }
        });
        
        // Add hover effect
        row.style.cursor = 'pointer';
    });
    
    // Status badge click to toggle (would require AJAX endpoint)
    const statusBadges = document.querySelectorAll('.status-badge');
    
    statusBadges.forEach(badge => {
        badge.addEventListener('click', function(e) {
            e.stopPropagation();
            // This would require AJAX endpoint to toggle status
            console.log('Status toggle would happen here');
        });
    });
    
    // Search and filter functionality
    const searchInput = document.getElementById('search-posts');
    
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            const tableRows = document.querySelectorAll('.posts-table tbody tr');
            
            tableRows.forEach(row => {
                const title = row.querySelector('td:first-child').textContent.toLowerCase();
                const category = row.querySelector('.category-badge').textContent.toLowerCase();
                
                if (title.includes(searchTerm) || category.includes(searchTerm)) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        });
    }
    
    // Password confirmation validation
    const newPasswordField = document.getElementById('new_password');
    const confirmPasswordField = document.getElementById('confirm_password');
    
    if (newPasswordField && confirmPasswordField) {
        function validatePasswordMatch() {
            const newPassword = newPasswordField.value;
            const confirmPassword = confirmPasswordField.value;
            
            if (newPassword && confirmPassword && newPassword !== confirmPassword) {
                confirmPasswordField.setCustomValidity('Passwords do not match');
            } else {
                confirmPasswordField.setCustomValidity('');
            }
        }
        
        newPasswordField.addEventListener('input', validatePasswordMatch);
        confirmPasswordField.addEventListener('input', validatePasswordMatch);
    }
    
    // Account form validation
    const accountForm = document.querySelector('.account-form');
    
    if (accountForm) {
        accountForm.addEventListener('submit', function(e) {
            const currentPassword = document.getElementById('current_password').value;
            const newPassword = document.getElementById('new_password').value;
            const confirmPassword = document.getElementById('confirm_password').value;
            
            if (!currentPassword) {
                e.preventDefault();
                alert('Current password is required to save changes.');
                document.getElementById('current_password').focus();
                return false;
            }
            
            if (newPassword && newPassword.length < 6) {
                e.preventDefault();
                alert('New password must be at least 6 characters long.');
                document.getElementById('new_password').focus();
                return false;
            }
            
            if (newPassword && newPassword !== confirmPassword) {
                e.preventDefault();
                alert('New passwords do not match.');
                document.getElementById('confirm_password').focus();
                return false;
            }
        });
    }
    
    // Mobile sidebar toggle
    const sidebarToggle = document.querySelector('.sidebar-toggle');
    const sidebar = document.querySelector('.admin-sidebar');
    
    if (sidebarToggle && sidebar) {
        sidebarToggle.addEventListener('click', function() {
            sidebar.classList.toggle('active');
        });
    }
    
    // Category form validation
    const categoryForm = document.querySelector('.category-form');
    
    if (categoryForm) {
        categoryForm.addEventListener('submit', function(e) {
            const name = document.getElementById('name').value.trim();
            
            if (!name) {
                e.preventDefault();
                alert('Category name is required.');
                document.getElementById('name').focus();
                return false;
            }
            
            if (name.length < 2) {
                e.preventDefault();
                alert('Category name must be at least 2 characters long.');
                document.getElementById('name').focus();
                return false;
            }
        });
    }
    
    // Auto-generate slug preview (optional enhancement)
    const nameField = document.getElementById('name');
    
    if (nameField) {
        nameField.addEventListener('input', function() {
            const name = this.value.trim();
            const slug = name.toLowerCase()
                .replace(/[^a-z0-9-]+/g, '-')
                .replace(/^-+|-+$/g, '');
            
            // Show slug preview if there's a preview element
            const slugPreview = document.getElementById('slug-preview');
            if (slugPreview) {
                slugPreview.textContent = slug || 'category-slug';
            }
        });
    }
});