/**
 * Keyword Association JavaScript
 */
(function($) {
    'use strict';

    $(document).ready(function() {
        // Handle category change for keywords
        $('.keyword-category-select').on('change', function() {
            const keywordId = $(this).data('keyword-id');
            const categoryId = $(this).val();
            
            updateKeywordCategory(keywordId, categoryId);
        });
    });

    /**
     * Update keyword category via AJAX
     * 
     * @param {number} keywordId The keyword ID
     * @param {number} categoryId The category ID
     */
    function updateKeywordCategory(keywordId, categoryId) {
        // Show loading indicator
        const row = $(`#keyword-row-${keywordId}`);
        const statusCell = row.find('.status-cell');
        
        statusCell.html('<span class="loading">Updating...</span>');
        
        // Make AJAX request
        $.ajax({
            url: aysa_ajax_object.ajax_url,
            type: 'POST',
            data: {
                action: 'update_keyword_category',
                nonce: aysa_ajax_object.nonce,
                keyword_id: keywordId,
                category_id: categoryId
            },
            success: function(response) {
                if (response.success) {
                    statusCell.html('<span class="success">Updated! Category: ' + response.data.category_name + '</span>');
                    
                    // Fade out success message after 3 seconds
                    setTimeout(function() {
                        statusCell.find('.success').fadeOut(500, function() {
                            $(this).remove();
                        });
                    }, 3000);
                } else {
                    statusCell.html('<span class="error">Error: ' + (response.data.message || 'Unknown error') + '</span>');
                }
            },
            error: function() {
                statusCell.html('<span class="error">Connection error. Please try again.</span>');
            }
        });
    }

    /**
     * Initialize keyword filter functionality
     */
    function initKeywordFilter() {
        $('#keyword-filter').on('keyup', function() {
            const searchTerm = $(this).val().toLowerCase();
            
            $('.keyword-table tbody tr').each(function() {
                const keywordText = $(this).find('.keyword-text').text().toLowerCase();
                
                if (keywordText.includes(searchTerm)) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        });
    }

    // Initialize all functions
    function init() {
        initKeywordFilter();
    }

    // Call init
    init();

})(jQuery); 