/*
|--------------------------------------------------------------------------
| Comments Admin JavaScript
|--------------------------------------------------------------------------
*/

document.addEventListener('DOMContentLoaded', function() {
    
    let selectedComments = [];
    const bulkActions = document.getElementById('bulkActions');
    const selectedCount = document.getElementById('selectedCount');

    // ========================================
    // Selection
    // ========================================
    window.updateSelection = function() {
        const checkboxes = document.querySelectorAll('.comment-checkbox:checked');
        selectedComments = Array.from(checkboxes).map(cb => parseInt(cb.value));
        
        if (selectedCount) {
            selectedCount.textContent = selectedComments.length;
        }
        
        if (bulkActions) {
            bulkActions.style.display = selectedComments.length > 0 ? 'flex' : 'none';
        }
    };

    // ========================================
    // Filters
    // ========================================
    const filterStatus = document.getElementById('filterStatus');
    const filterAnswered = document.getElementById('filterAnswered');
    const filterRating = document.getElementById('filterRating');
    const searchInput = document.getElementById('searchInput');

    function applyFilters() {
        const params = new URLSearchParams(window.location.search);
        
        if (filterStatus?.value) params.set('status', filterStatus.value);
        else params.delete('status');
        
        if (filterAnswered?.value) params.set('answered', filterAnswered.value);
        else params.delete('answered');
        
        if (filterRating?.value) params.set('rating', filterRating.value);
        else params.delete('rating');
        
        if (searchInput?.value) params.set('search', searchInput.value);
        else params.delete('search');
        
        window.location.href = window.location.pathname + '?' + params.toString();
    }

    filterStatus?.addEventListener('change', applyFilters);
    filterAnswered?.addEventListener('change', applyFilters);
    filterRating?.addEventListener('change', applyFilters);

    let searchTimeout;
    searchInput?.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(applyFilters, 500);
    });

    // ========================================
    // Toggle Replies
    // ========================================
    window.toggleReplies = function(btn) {
        const commentItem = btn.closest('.comment-item');
        const replies = commentItem.querySelector('.comment-replies');
        
        if (replies) {
            replies.classList.toggle('collapsed');
            btn.classList.toggle('collapsed');
        }
    };

    // ========================================
    // Approve Comment
    // ========================================
    window.approveComment = async function(id) {
        const url = COMMENTS_CONFIG.routes.approve.replace(':id', id);
        
        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content,
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }
            });
            const data = await response.json();
            
            if (data.success) {
                showToast('success', data.message);
                updateCommentStatus(id, 'approved');
            } else {
                showToast('error', data.message || COMMENTS_CONFIG.translations.error);
            }
        } catch (error) {
            console.error('Error:', error);
            showToast('error', COMMENTS_CONFIG.translations.error);
        }
    };

    // ========================================
    // Reject Comment
    // ========================================
    window.rejectComment = async function(id) {
        const url = COMMENTS_CONFIG.routes.reject.replace(':id', id);
        
        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content,
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }
            });
            const data = await response.json();
            
            if (data.success) {
                showToast('success', data.message);
                updateCommentStatus(id, 'rejected');
            } else {
                showToast('error', data.message || COMMENTS_CONFIG.translations.error);
            }
        } catch (error) {
            console.error('Error:', error);
            showToast('error', COMMENTS_CONFIG.translations.error);
        }
    };

    // ========================================
    // Mark as Spam
    // ========================================
    window.markAsSpam = async function(id) {
        const url = COMMENTS_CONFIG.routes.spam.replace(':id', id);
        
        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content,
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }
            });
            const data = await response.json();
            
            if (data.success) {
                showToast('success', data.message);
                updateCommentStatus(id, 'spam');
            } else {
                showToast('error', data.message || COMMENTS_CONFIG.translations.error);
            }
        } catch (error) {
            console.error('Error:', error);
            showToast('error', COMMENTS_CONFIG.translations.error);
        }
    };

    // ========================================
    // Update Comment Status in UI
    // ========================================
    function updateCommentStatus(id, status) {
        const commentItem = document.querySelector(`.comment-item[data-id="${id}"]`);
        if (!commentItem) return;
        
        // Remove old status classes
        commentItem.classList.remove('pending', 'approved', 'rejected', 'spam');
        commentItem.classList.add(status);
        
        // Update status badge
        const statusBadge = commentItem.querySelector('.comment-status');
        if (statusBadge) {
            statusBadge.className = `comment-status status-${status}`;
            statusBadge.textContent = status.charAt(0).toUpperCase() + status.slice(1);
        }
        
        // Update action buttons visibility
        const approveBtn = commentItem.querySelector('.btn-approve');
        const rejectBtn = commentItem.querySelector('.btn-reject');
        
        if (approveBtn) approveBtn.style.display = status === 'approved' ? 'none' : '';
        if (rejectBtn) rejectBtn.style.display = status === 'rejected' ? 'none' : '';
    }

    // ========================================
    // Delete Comment
    // ========================================
    window.deleteComment = function(id) {
        const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
        deleteModal.show();
        
        document.getElementById('btnConfirmDelete').onclick = async function() {
            const url = COMMENTS_CONFIG.routes.destroy.replace(':id', id);
            
            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content,
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    }
                });
                const data = await response.json();
                
                if (data.success) {
                    document.querySelector(`.comment-item[data-id="${id}"]`)?.remove();
                    deleteModal.hide();
                    showToast('success', data.message);
                } else {
                    showToast('error', data.message || COMMENTS_CONFIG.translations.error);
                }
            } catch (error) {
                console.error('Error:', error);
                showToast('error', COMMENTS_CONFIG.translations.error);
            }
        };
    };

    // ========================================
    // Bulk Actions
    // ========================================
    window.bulkAction = async function(action) {
        if (selectedComments.length === 0) return;
        
        if (action === 'delete' && !confirm('Are you sure you want to delete selected comments?')) {
            return;
        }
        
        try {
            const response = await fetch(COMMENTS_CONFIG.routes.bulk, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content,
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({
                    ids: selectedComments,
                    action: action
                })
            });
            const data = await response.json();
            
            if (data.success) {
                showToast('success', data.message);
                
                if (action === 'delete') {
                    selectedComments.forEach(id => {
                        document.querySelector(`.comment-item[data-id="${id}"]`)?.remove();
                    });
                } else {
                    selectedComments.forEach(id => {
                        updateCommentStatus(id, action === 'approve' ? 'approved' : action === 'reject' ? 'rejected' : 'spam');
                    });
                }
                
                // Clear selection
                document.querySelectorAll('.comment-checkbox:checked').forEach(cb => cb.checked = false);
                selectedComments = [];
                updateSelection();
            } else {
                showToast('error', data.message || COMMENTS_CONFIG.translations.error);
            }
        } catch (error) {
            console.error('Error:', error);
            showToast('error', COMMENTS_CONFIG.translations.error);
        }
    };

    // ========================================
    // Reply Modal
    // ========================================
    window.openReplyModal = function(parentId = null, authorName = null) {
        document.getElementById('replyParentId').value = parentId || '';
        document.getElementById('replyContent').value = '';
        
        const replyToInfo = document.getElementById('replyToInfo');
        const replyToContent = document.getElementById('replyToContent');
        
        if (parentId && authorName) {
            replyToInfo.style.display = 'block';
            replyToContent.textContent = `@${authorName}`;
        } else {
            replyToInfo.style.display = 'none';
        }
        
        const replyModal = new bootstrap.Modal(document.getElementById('replyModal'));
        replyModal.show();
    };

    window.submitReply = async function() {
        const content = document.getElementById('replyContent').value.trim();
        const parentId = document.getElementById('replyParentId').value;
        
        if (!content) {
            showToast('error', 'Please enter a reply');
            return;
        }
        
        try {
            const response = await fetch(COMMENTS_CONFIG.routes.store, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content,
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({
                    content: content,
                    parent_id: parentId || null
                })
            });
            const data = await response.json();
            
            if (data.success) {
                showToast('success', data.message);
                bootstrap.Modal.getInstance(document.getElementById('replyModal'))?.hide();
                
                // Reload page to show new comment
                setTimeout(() => window.location.reload(), 500);
            } else {
                showToast('error', data.message || COMMENTS_CONFIG.translations.error);
            }
        } catch (error) {
            console.error('Error:', error);
            showToast('error', COMMENTS_CONFIG.translations.error);
        }
    };

    // ========================================
    // Toast Notifications
    // ========================================
    function showToast(type, message) {
        // Check if Viartas theme toast exists
        if (typeof window.viartasToast === 'function') {
            window.viartasToast(type, message);
            return;
        }
        
        // Fallback toast
        const toastContainer = document.querySelector('.toast-container') || createToastContainer();
        
        const toast = document.createElement('div');
        toast.className = `toast align-items-center text-white bg-${type === 'success' ? 'success' : 'danger'} border-0`;
        toast.setAttribute('role', 'alert');
        toast.innerHTML = `
            <div class="d-flex">
                <div class="toast-body">${message}</div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        `;
        
        toastContainer.appendChild(toast);
        const bsToast = new bootstrap.Toast(toast, { delay: 3000 });
        bsToast.show();
        
        toast.addEventListener('hidden.bs.toast', () => toast.remove());
    }

    function createToastContainer() {
        const container = document.createElement('div');
        container.className = 'toast-container position-fixed top-0 end-0 p-3';
        container.style.zIndex = '1100';
        document.body.appendChild(container);
        return container;
    }

});
