jQuery(document).ready(function($) {
    
    // Sortable functionality
    $('#pc-faq-sortable').sortable({
        handle: '.sort-handle',
        placeholder: 'pc-faq-sortable-placeholder',
        helper: 'clone',
        opacity: 0.9,
        cursor: 'move',
        tolerance: 'pointer',
        start: function(event, ui) {
            ui.placeholder.height(ui.item.outerHeight());
        },
        update: function(event, ui) {
            $('#pc-faq-save-order').addClass('highlight');
        }
    });
    
    // Save order
    $('#pc-faq-save-order').on('click', function() {
        var $button = $(this);
        var $status = $('.pc-faq-save-status');
        
        if ($button.prop('disabled')) {
            return;
        }
        
        var faqIds = [];
        $('#pc-faq-sortable .pc-faq-item').each(function() {
            faqIds.push($(this).data('faq-id'));
        });
        
        $button.prop('disabled', true);
        $status.text(pc_faq_manager.saving).removeClass('saved error').addClass('saving');
        
        $.post(pc_faq_manager.ajax_url, {
            action: 'pc_faq_reorder',
            nonce: pc_faq_manager.nonce,
            faq_ids: faqIds
        })
        .done(function(response) {
            if (response.success) {
                $status.text(pc_faq_manager.saved).removeClass('saving error').addClass('saved');
                $button.removeClass('highlight');
            } else {
                $status.text(pc_faq_manager.error).removeClass('saving saved').addClass('error');
            }
        })
        .fail(function() {
            $status.text(pc_faq_manager.error).removeClass('saving saved').addClass('error');
        })
        .always(function() {
            $button.prop('disabled', false);
            setTimeout(function() {
                $status.text('').removeClass('saving saved error');
            }, 3000);
        });
    });
    
    // Edit FAQ modal
    var $modal = $('#pc-faq-edit-modal');
    var $backdrop = $('.pc-faq-modal-backdrop');
    var currentEditingId = null;
    
    function openEditModal(faqId) {
        var $item = $('.pc-faq-item[data-faq-id="' + faqId + '"]');
        var title = $item.find('.faq-question h4').text();
        var content = $item.find('.faq-content').text();
        
        $('#pc-faq-edit-title').val(title);
        $('#pc-faq-edit-content').val(content);
        currentEditingId = faqId;
        
        $modal.show();
        $backdrop.show();
        $('body').css('overflow', 'hidden');
    }
    
    function closeEditModal() {
        $modal.hide();
        $backdrop.hide();
        $('body').css('overflow', '');
        currentEditingId = null;
    }
    
    $('.pc-faq-edit').on('click', function() {
        var faqId = $(this).data('faq-id');
        openEditModal(faqId);
    });
    
    $('.pc-faq-modal-close, .pc-faq-modal-cancel, .pc-faq-modal-backdrop').on('click', function() {
        closeEditModal();
    });
    
    // Save edited FAQ
    $('.pc-faq-modal-save').on('click', function() {
        if (!currentEditingId) {
            return;
        }
        
        var $button = $(this);
        var title = $('#pc-faq-edit-title').val().trim();
        var content = $('#pc-faq-edit-content').val();
        
        if (!title || !content) {
            alert('Please fill in both the question and answer.');
            return;
        }
        
        if ($button.prop('disabled')) {
            return;
        }
        
        $button.prop('disabled', true);
        
        $.post(pc_faq_manager.ajax_url, {
            action: 'pc_faq_edit',
            nonce: pc_faq_manager.nonce,
            faq_id: currentEditingId,
            title: title,
            content: content
        })
        .done(function(response) {
            if (response.success) {
                // Update the item in the list
                var $item = $('.pc-faq-item[data-faq-id="' + currentEditingId + '"]');
                $item.find('.faq-question h4').text(title);
                $item.find('.faq-content').text(content.replace(/<[^>]*>/g, '').substring(0, 100) + '...');
                $item.find('.faq-excerpt').text(content.replace(/<[^>]*>/g, '').substring(0, 50) + '...');
                
                closeEditModal();
            } else {
                alert('Failed to update FAQ: ' + (response.data.message || 'Unknown error'));
            }
        })
        .fail(function() {
            alert('Failed to update FAQ. Please try again.');
        })
        .always(function() {
            $button.prop('disabled', false);
        });
    });
    
    // Delete FAQ
    $('.pc-faq-delete').on('click', function() {
        var $button = $(this);
        var faqId = $button.data('faq-id');
        var $item = $button.closest('.pc-faq-item');
        
        if (!confirm(pc_faq_manager.confirm_delete)) {
            return;
        }
        
        if ($button.prop('disabled')) {
            return;
        }
        
        $button.prop('disabled', true);
        
        $.post(pc_faq_manager.ajax_url, {
            action: 'pc_faq_delete',
            nonce: pc_faq_manager.nonce,
            faq_id: faqId
        })
        .done(function(response) {
            if (response.success) {
                $item.fadeOut(300, function() {
                    $(this).remove();
                    
                    // Check if we need to show empty state
                    var remainingItems = $('#pc-faq-sortable .pc-faq-item').length;
                    if (remainingItems === 0) {
                        location.reload();
                    }
                });
            } else {
                alert('Failed to delete FAQ: ' + (response.data.message || 'Unknown error'));
            }
        })
        .fail(function() {
            alert('Failed to delete FAQ. Please try again.');
        })
        .always(function() {
            $button.prop('disabled', false);
        });
    });
    
    // Add new FAQ form
    $('#pc-faq-add-form').on('submit', function(e) {
        e.preventDefault();
        
        var $form = $(this);
        var $button = $form.find('button[type="submit"]');
        var title = $('#pc-faq-title').val().trim();
        var content = $('#pc-faq-content').val();
        
        if (!title || !content) {
            showMessage('Please fill in both the question and answer.', 'error');
            return;
        }
        
        if ($button.prop('disabled')) {
            return;
        }
        
        $button.prop('disabled', true);
        
        $.post(pc_faq_manager.ajax_url, {
            action: 'pc_faq_add_new',
            nonce: pc_faq_manager.nonce,
            title: title,
            content: content
        })
        .done(function(response) {
            if (response.success) {
                showMessage('FAQ created successfully! Redirecting...', 'success');
                setTimeout(function() {
                    window.location.href = 'admin.php?page=pc-faq-manager';
                }, 1500);
            } else {
                showMessage('Failed to create FAQ: ' + (response.data.message || 'Unknown error'), 'error');
            }
        })
        .fail(function() {
            showMessage('Failed to create FAQ. Please try again.', 'error');
        })
        .always(function() {
            $button.prop('disabled', false);
        });
    });
    
    function showMessage(message, type) {
        var $message = $('#pc-faq-add-message');
        $message.removeClass('notice-success notice-error')
               .addClass('notice-' + type)
               .html('<p>' + message + '</p>')
               .show();
        
        setTimeout(function() {
            $message.fadeOut();
        }, 5000);
    }
    
    // ESC key to close modal
    $(document).on('keydown', function(e) {
        if (e.keyCode === 27 && $modal.is(':visible')) {
            closeEditModal();
        }
    });
});