jQuery(document).ready(function($) {
    // Initialize active filters
    var activeFilters = {
        type: 'all',
        category: 'all'
    };
    
    // Count initial widgets per category
    updateCategoryCounts();

    // Filter functionality
    function filterWidgets() {
        var search = ($('#asa-widget-search').val() || '').toLowerCase();
        var visibleCount = 0;

        $('.asa-widget-item').each(function() {
            var $item = $(this);
            var itemType = $item.data('type');
            var itemCategory = $item.data('category');
            var itemTitle = $item.find('h3').text().toLowerCase();
            var isLocked = $item.hasClass('asa-widget-locked');

            var typeMatch = activeFilters.type === 'all' || itemType === activeFilters.type;
            var categoryMatch = activeFilters.category === 'all' || itemCategory === activeFilters.category;
            var searchMatch = search === '' || itemTitle.includes(search);

            if (typeMatch && categoryMatch && searchMatch) {
                $item.show();
                visibleCount++;
            } else {
                $item.hide();
            }
        });
        
        // Update counts after filtering
        updateCategoryCounts();
    }
    
    // Update category counts
    function updateCategoryCounts() {
        var counts = {};
        
        // Initialize counts for all categories
        $('.asa-category-tab').each(function() {
            var category = $(this).data('category');
            counts[category] = 0;
        });
        
        // Count visible widgets per category
        var typeFilter = activeFilters.type;
        var search = ($('#asa-widget-search').val() || '').toLowerCase();
        
        $('.asa-widget-item').each(function() {
            var $item = $(this);
            var itemType = $item.data('type');
            var itemCategory = $item.data('category');
            var itemTitle = $item.find('h3').text().toLowerCase();
            var isLocked = $item.hasClass('asa-widget-locked');
            
            var typeMatch = activeFilters.type === 'all' || itemType === activeFilters.type;
            var searchMatch = search === '' || itemTitle.includes(search);
            
            if (typeMatch && searchMatch) {
                // Count for specific category
                counts[itemCategory]++;
                
                // Also count for 'all' category
                counts['all']++;
            }
        });
        
        // Update the count display
        $('.asa-category-count').each(function() {
            var category = $(this).data('category');
            $(this).text(counts[category]);
        });
    }

    // Handle filter button clicks
    $('.asa-filter-button').on('click', function() {
        var filterType = $(this).data('filter');
        var filterValue = $(this).data('value');

        // Update active filter
        activeFilters[filterType] = filterValue;

        // Update button states
        $('.asa-filter-button[data-filter="' + filterType + '"]').removeClass('active');
        $(this).addClass('active');

        filterWidgets();
    });
    
    // Handle category tab clicks
    $('.asa-category-tab').on('click', function(e) {
        e.preventDefault();
        
        var category = $(this).data('category');
        
        // Update active filter
        activeFilters.category = category;
        
        // Update tab states
        $('.asa-category-tab').removeClass('active');
        $(this).addClass('active');
        
        filterWidgets();
    });

    // Handle search input
    $('#asa-widget-search').on('input', filterWidgets);

    // Activate/Deactivate all
    $('#activate-all').on('click', function() {
        $('.asa-widget-item:visible:not(.asa-widget-locked) input[type="checkbox"]').prop('checked', true);
    });

    $('#deactivate-all').on('click', function() {
        $('.asa-widget-item:visible:not(.asa-widget-locked) input[type="checkbox"]').prop('checked', false);
    });

    // Set initial active states
    $('.asa-filter-button[data-value="all"]').addClass('active');
    
    // Initial filter to show counts
    filterWidgets();
    
    // Handle locked widget interactions
    $('.asa-widget-locked').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        // Show notification about pro requirement
        var $notification = $('#asa-notification');
        $notification
            .removeClass('success')
            .addClass('error')
            .find('.asa-notification-message')
            .html('<span class="dashicons dashicons-lock"></span> This widget requires Atomic Slider Pro to be activated.');
        
        $notification.fadeIn();
        
        // Hide notification after 3 seconds
        setTimeout(function() {
            $notification.fadeOut();
        }, 3000);
    });

    // Handle form submission
    $('#asa-widgets-form').on('submit', function(e) {
        e.preventDefault();
        
        var $form = $(this);
        var $submitButton = $('#save-widgets');
        var $notification = $('#asa-notification');
        
        // Disable submit button and show loading state
        $submitButton.prop('disabled', true).addClass('loading');
        
        // Collect form data
        var formData = new FormData(this);
        formData.append('action', 'atomicslider_save_widgets');
        
        // Check if atomicSlider object exists and add security nonce
        if (typeof atomicSlider !== 'undefined' && atomicSlider.security) {
            formData.append('security', atomicSlider.security);
        } else {
            console.error('Security nonce not found. Form submission may fail.');
        }
        
        // Send AJAX request
        $.ajax({
            url: typeof atomicSlider !== 'undefined' && atomicSlider.ajaxurl ? atomicSlider.ajaxurl : ajaxurl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    // Show success notification
                    $notification
                        .removeClass('error')
                        .addClass('success')
                        .find('.asa-notification-message')
                        .html('<span class="dashicons dashicons-yes"></span> ' + response.data.message);
                } else {
                    // Show error notification
                    $notification
                        .removeClass('success')
                        .addClass('error')
                        .find('.asa-notification-message')
                        .html('<span class="dashicons dashicons-warning"></span> ' + response.data.message);
                }
                
                // Show notification
                $notification.fadeIn();
                
                // Hide notification after 3 seconds
                setTimeout(function() {
                    $notification.fadeOut();
                }, 3000);
            },
            error: function() {
                // Get error message from localized data or use default
                var errorMessage = 'An error occurred while saving. Please try again.';
                if (typeof atomicSlider !== 'undefined' && atomicSlider.i18n && atomicSlider.i18n.errorMessage) {
                    errorMessage = atomicSlider.i18n.errorMessage;
                }
                
                // Show error notification
                $notification
                    .removeClass('success')
                    .addClass('error')
                    .find('.asa-notification-message')
                    .html('<span class="dashicons dashicons-warning"></span> ' + errorMessage)
                    .fadeIn();
                
                // Hide notification after 3 seconds
                setTimeout(function() {
                    $notification.fadeOut();
                }, 3000);
            },
            complete: function() {
                // Re-enable submit button and remove loading state
                $submitButton.prop('disabled', false).removeClass('loading');
            }
        });
    });
});