/**
 * Fixes Overview Tab Module
 * Handles the display and pagination of fixed items
 */
(function($, rank) {
    'use strict';

    // Cache elements
    const $fixesAccordion = $('#rank-fixes-accordion');

    // --- Fixes Overview Tab Logic ---

    // Function to fetch and display initial counts for all categories
    function loadInitialFixCounts() {
        // Check if the accordion exists on the current page view
        if (!$fixesAccordion.length) {
            return; // Exit if not on the Fixes Overview tab
        }

        $.ajax({
            url: rank_ajax_obj.ajax_url,
            type: 'POST',
            data: {
                action: 'rank_get_all_fix_counts',
                nonce: rank_ajax_obj.nonce
            },
            dataType: 'json',
            success: function(response) {
                if (response.success && response.data) {
                    const counts = response.data;
                    // Check if there are any fixes
                    let totalFixes = 0;
                    
                    // Loop through each accordion header
                    $fixesAccordion.find('.rank-accordion-header').each(function() {
                        const $header = $(this);
                        const category = $header.data('category');
                        const issueType = $header.data('issue-type') || category;
                        const $countSpan = $header.find('.rank-accordion-count');
                        let count = 0;

                        // Check if we have a count for this specific issue type
                        if (counts.hasOwnProperty(issueType)) {
                            count = parseInt(counts[issueType]);
                            $countSpan.text(`✅ ${count}`); // Update text with count
                        } else if (counts.hasOwnProperty(category)) {
                            // Fallback to category if issue type not found
                            count = parseInt(counts[category]);
                            $countSpan.text(`✅ ${count}`);
                        } else {
                            $countSpan.text('0'); // Default to 0 if not found in response
                        }
                        
                        totalFixes += count;
                    });
                    
                    // Update the description paragraph based on whether fixes were found
                    const $descriptionParagraph = $('.rank-section p:contains("Expand by clicking")');
                    if (totalFixes === 0) {
                        // No fixes found - show warning message with link to fix problems tab
                        $descriptionParagraph.html('⚠️ No fixes found. <a href="?page=rank-admin&tab=bulk_fix">Go here to fix problems.</a>');
                    } else {
                        // Keep original text if fixes were found
                        if ($descriptionParagraph.text().includes('⚠️')) {
                            $descriptionParagraph.text('Expand by clicking on each to see and edit the changes applied by RANK AI.');
                        }
                    }
                    
                    // Hide the tab content loader after all counts are loaded
                    $('.tab-content-loader').fadeOut(300);
                } else {
                    // Handle error fetching counts
                    $fixesAccordion.find('.rank-accordion-count').text('(?)');
                    console.error('Error fetching fix counts:', response.data || 'Unknown error');
                    
                    // Use helper if available
                    if (rank.helpers && rank.helpers.showNotice) {
                        rank.helpers.showNotice('Could not load fix counts.', 'warning');
                    }
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                $fixesAccordion.find('.rank-accordion-count').text('(?)');
                console.error(`AJAX Error fetching fix counts: ${textStatus} - ${errorThrown}`);
                
                // Use helper if available
                if (rank.helpers && rank.helpers.showNotice) {
                    rank.helpers.showNotice(`Error loading fix counts: ${textStatus}`, 'error');
                }
                
                // Hide the tab content loader even if there's an error
                $('.tab-content-loader').fadeOut(300);
            }
        });
    }

    // Delete All Button Click Handler
    $fixesAccordion.on('click', '.rank-delete-all-btn', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        const $btn = $(this);
        const category = $btn.data('category');
        const issueType = $btn.data('issue-type') || category;
        const $item = $btn.closest('.rank-accordion-item');
        const $header = $item.find('.rank-accordion-header');
        const categoryLabel = $header.find('span').first().text();
        
        // Confirm deletion
        const confirmMessage = `Are you sure you want to delete ALL fixes in "${categoryLabel}"?\n\nThis action cannot be undone.`;
        if (!confirm(confirmMessage)) {
            return;
        }
        
        // Show loading state
        const originalText = $btn.html();
        $btn.prop('disabled', true).html('<span class="dashicons dashicons-update" style="animation: spin 1s linear infinite;"></span> Deleting...');
        
        // Make AJAX request
        $.ajax({
            url: rank_ajax_obj.ajax_url,
            type: 'POST',
            data: {
                action: 'rank_delete_category_fixes',
                nonce: rank_ajax_obj.nonce,
                category: category,
                issue_type: issueType
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    // Show success message
                    $btn.html('<span class="dashicons dashicons-yes-alt" style="color: #46b450;"></span> Deleted');
                    
                    // Reload the fixes data if accordion is open
                    if ($header.hasClass('rank-accordion-open')) {
                        // Reset loaded flag and reload
                        $item.data('loaded', false);
                        loadFixesData(category, 1, $item);
                    }
                    
                    // Reload initial counts
                    loadInitialFixCounts();
                    
                    // Reset button after 2 seconds
                    setTimeout(function() {
                        $btn.prop('disabled', false).html(originalText);
                    }, 2000);
                } else {
                    alert('Error: ' + (response.data && response.data.message ? response.data.message : 'Failed to delete fixes'));
                    $btn.prop('disabled', false).html(originalText);
                }
            },
            error: function(xhr, status, error) {
                alert('Error: Failed to delete fixes. Please try again.');
                $btn.prop('disabled', false).html(originalText);
            }
        });
    });
    // CSV Export Button Click Handler
    $fixesAccordion.on('click', '.rank-csv-export-btn', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        const $btn = $(this);
        const category = $btn.data('category');
        const issueType = $btn.data('issue-type') || category;
        
        // Build the download URL
        const downloadUrl = rank_ajax_obj.ajax_url + 
            '?action=rank_export_category_csv' +
            '&category=' + encodeURIComponent(category) +
            '&issue_type=' + encodeURIComponent(issueType) +
            '&nonce=' + encodeURIComponent(rank_ajax_obj.nonce);
        
        // Trigger download by navigating to the URL
        window.location.href = downloadUrl;
    });


    // Accordion Header Click
    $fixesAccordion.on('click', '.rank-accordion-header', function(e) {
        const $header = $(this);
        const $item = $header.closest('.rank-accordion-item');
        const $content = $item.find('.rank-accordion-content');
        const category = $header.data('category');
        const isOpen = $header.hasClass('rank-accordion-open');
        const $countSpan = $header.find('.rank-accordion-count');
        
        // Ensure the count text starts with a checkmark if it doesn't already
        const countText = $countSpan.text();
        if (!countText.startsWith('✅')) {
            $countSpan.text(`✅ ${countText}`);
        }

        if (isOpen) {
            // Close the accordion
            $content.slideUp(200);
            $header.removeClass('rank-accordion-open');
        } else {
            // Open the accordion
            $content.slideDown(200);
            $header.addClass('rank-accordion-open');

            // Load data if it hasn't been loaded yet for this item
            if (!$item.data('loaded')) {
                loadFixesData(category, 1, $item); // Load page 1
            }
        }
    });

    // Function to load fixes data via AJAX (for a single category when expanded)
    function loadFixesData(category, page, $item, searchQuery = '', perPage = null) {
        const $content = $item.find('.rank-accordion-content');
        const $tableContainer = $content.find('.rank-accordion-table-container');
        const $paginationContainer = $content.find('.rank-accordion-pagination');
        const $loading = $content.find('.rank-accordion-loading');
        const $noData = $content.find('.rank-accordion-no-data');
        const $header = $item.find('.rank-accordion-header');
        const $countSpan = $header.find('.rank-accordion-count');
        const issueType = $header.data('issue-type') || category;

        // Get per_page from stored data or use provided value or default
        if (perPage === null) {
            perPage = $item.data('per-page') || 20;
        }
        $item.data('per-page', perPage); // Store for future use

        $loading.show();
        $noData.hide();
        $tableContainer.find('.rank-fixes-table').remove(); // Clear previous table
        $paginationContainer.empty(); // Clear previous pagination

        $.ajax({
            url: rank_ajax_obj.ajax_url,
            type: 'POST',
            data: {
                action: 'rank_get_fixes_data',
                nonce: rank_ajax_obj.nonce,
                category: category,
                issue_type: issueType,
                page: page,
                search_query: searchQuery,
                per_page: perPage
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    $item.data('loaded', true); // Mark as loaded (at least once)
                    const data = response.data;

                    // Update count in header, always keeping the checkmark
                    // Ensure we always show the checkmark, even for 0 count
                    $countSpan.text(`✅ ${data.total_items}`);

                    if (data.items && data.items.length > 0) {
                        
                        // Build Table
                        displayFixesData(data, $tableContainer, category);

                        // Build Pagination
                        displayPagination(data, $paginationContainer, category, $item);

                    } else {
                        $noData.show();
                        // Ensure we keep the checkmark for 0 items
                        if (data.total_items === 0) {
                            $countSpan.text(`✅ 0`);
                        }
                    }
                } else {
                    $noData.text('Error loading data: ' + (response.data || 'Unknown error')).show();
                    $countSpan.text('(?)'); // Keep (?) on error
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                $noData.text(`AJAX Error loading data: ${textStatus}`).show();
                $countSpan.text('(?)'); // Keep (?) on AJAX error
            },
            complete: function() {
                $loading.hide();
            }
        });
    }

    // Function to display fetched fixes data in a table
    function displayFixesData(data, $tableContainer, category) {
        $tableContainer.empty(); // Clear previous table/messages

        // Static message that appears at the top of accordion content
        const staticMessage = '<div class="rank-fixes-notice" style="background-color: #fff3cd; border: 1px solid #ffeaa7; border-radius: 4px; padding: 10px; margin-bottom: 15px; color: #856404;">' +
            'Fixes will only show up when visiting the website. Not in WP admin. Expect 80% success rate. ' +
            '<a href="https://morningscore.io/automatic-seo-wordpress-plugin-rank-ai/#lwptoc10" target="_blank" style="color: #0073aa;">More info</a>' +
            '</div>';

        // Search interface
        const searchHtml = '<div class="rank-search-container" style="margin-bottom: 15px;">' +
            '<div style="display: flex; gap: 10px; align-items: stretch;">' +
                '<input type="text" class="rank-search-input" placeholder="Search by page URL" style="max-width: 250px; padding: 8px; border: 1px solid #ddd; border-radius: 4px; height: 32px; box-sizing: border-box;">' +
                '<button type="button" class="rank-search-btn button button-small" style="height: 32px; line-height: 1; padding: 0 12px;">Search</button>' +
                '<button type="button" class="rank-clear-search-btn button button-small" style="display: none; height: 32px; line-height: 1; padding: 0 12px;">Clear</button>' +
            '</div>' +
            '<div class="rank-search-results-info" style="margin-top: 5px; font-size: 12px; color: #666;"></div>' +
        '</div>';

        if (!data || !data.items || data.items.length === 0) {
            $tableContainer.html(staticMessage + searchHtml + '<p class="rank-accordion-no-data">No fixes found for this category.</p>');
            addSearchEventHandlers($tableContainer, category, $tableContainer.closest('.rank-accordion-item'));
            return;
        }

        let tableHtml = '<table class="wp-list-table widefat fixed striped rank-fixes-table">';
        tableHtml += '<thead><tr>';

        // Define headers based on category type
        const isOptionType = data.items[0].is_option; // Check the flag from the first item
        // Check for image alt tags using multiple possible category/issue type values
        const isImageType = category === 'image_alt' || category === 'missing_alt_tags' || (data.items[0].issue_type && data.items[0].issue_type.includes('alt_tag'));

        if (isOptionType) {
            tableHtml += '<th scope="col">Page</th>';
            tableHtml += '<th scope="col">Broken URL</th>';
            tableHtml += '<th scope="col">Fixed URL</th>';
        } else if (isImageType) {
            tableHtml += '<th scope="col">Page</th>';
            tableHtml += '<th scope="col">Image Preview</th>';
            tableHtml += '<th scope="col">Image URL</th>';
            tableHtml += '<th scope="col">New Alt Text</th>';
        } else { // Standard DB types (Title, Meta Desc)
            tableHtml += '<th scope="col">Page</th>';
            tableHtml += '<th scope="col">New Value</th>';
        }
        tableHtml += '</tr></thead>';
        tableHtml += '<tbody>';

        data.items.forEach(item => {
            tableHtml += '<tr>';
            if (isOptionType) {
                // For broken links:
                // - context: contains the landing page URL (where the broken link was found)
                // - context_text: contains the old URL (the broken link)
                // - value: contains the new URL (replacement)
                
                // Get the landing page URL
                const landingPageUrl = item.context || '#';
                const displayUrl = landingPageUrl.replace(/^https?:\/\/[^\/]+/, ''); // Show relative URL for cleaner display
                
                // Display the landing page URL with safe link opening
                tableHtml += `<td><a href="javascript:void(0);" onclick="window.open('${landingPageUrl}','_blank');">${displayUrl || 'N/A'}</a></td>`;
                
                // Display the old URL
                // If context_text starts with row_key_, try to extract the real URL from row_key
                let displayOldUrl = item.context_text || 'N/A';
                
                if (item.row_key && displayOldUrl.startsWith('row_key_')) {
                    try {
                        // Try to decode the base64 row_key
                        const decodedData = JSON.parse(atob(item.row_key));
                        
                        // Check if we have a payload with issue_identifier
                        if (decodedData.payload) {
                            const payload = JSON.parse(decodedData.payload);
                            if (payload.issue_identifier) {
                                displayOldUrl = payload.issue_identifier;
                            }
                        }
                    } catch (e) {
                        // If decoding fails, keep using the original displayOldUrl
                        console.log('Error decoding row_key:', e);
                    }
                }
                
                // Clean up composite keys - remove ::context::hash part for display
                if (displayOldUrl && displayOldUrl.includes('::context::')) {
                    displayOldUrl = displayOldUrl.split('::context::')[0];
                }
                
                tableHtml += `<td>${displayOldUrl}</td>`;
                
                // Add edit icon to the replacement value
                tableHtml += `<td>
                    <span class="rank-editable-value">${item.value || 'N/A'}</span>
                    <span class="rank-edit-icon dashicons dashicons-edit" data-type="${category}" data-is-option="true" data-old-url="${encodeURIComponent(item.context_text || '')}" data-issue-type="${item.issue_type || category}"></span>
                    <span class="rank-delete-icon dashicons dashicons-trash" data-type="${category}" data-is-option="true" data-old-url="${encodeURIComponent(item.context_text || '')}" data-issue-type="${item.issue_type || category}"></span>
                </td>`;
            } else if (isImageType) {
                // Context is a link using context_text
                tableHtml += `<td><a href="javascript:void(0);" onclick="window.open('${item.context || '#'}','_blank');">${item.context_text || 'N/A'}</a></td>`;
                
                // Image preview column
                tableHtml += `<td>${item.image_src && item.image_src.startsWith('http') ? `<img src="${item.image_src}" alt="Preview" style="max-width: 50px; max-height: 50px; vertical-align: middle;">` : (item.image_src || 'N/A')}</td>`;
                
                // Image URL column - clickable link to open image in new tab
                // Extract the image ID from context_text which has format "... (Image ID: 12345)"
                let imageId = '';
                const imageIdMatch = item.context_text ? item.context_text.match(/\(Image ID: (\d+)\)/) : null;
                if (imageIdMatch && imageIdMatch[1]) {
                    imageId = imageIdMatch[1];
                }
                
                // Use image_src if available, otherwise construct URL from image ID
                const imageUrl = item.image_src || (imageId ? `/wp-admin/upload.php?item=${imageId}` : '#');
                const displayUrl = imageUrl.startsWith('http') ? imageUrl.split('/').pop() : imageUrl;
                
                tableHtml += `<td><a href="javascript:void(0);" onclick="window.open('${imageUrl}','_blank');">${displayUrl || 'N/A'}</a></td>`;
                
                // New alt text value with edit icon
                tableHtml += `<td>
                    <span class="rank-editable-value">${item.value || 'N/A'}</span>
                    <span class="rank-edit-icon dashicons dashicons-edit" data-post-id="${item.post_id || ''}" data-object-id="${item.object_id || ''}" data-type="${category}" data-issue-type="${item.issue_type || category}"></span>
                    <span class="rank-delete-icon dashicons dashicons-trash" data-post-id="${item.post_id || ''}" data-object-id="${item.object_id || ''}" data-type="${category}" data-issue-type="${item.issue_type || category}"></span>
                </td>`;
            } else { // Standard DB types
                // Context is a link using context_text
                tableHtml += `<td><a href="javascript:void(0);" onclick="window.open('${item.context || '#'}','_blank');">${item.context_text || 'N/A'}</a></td>`;
                // New value (Title or Meta Desc) with edit icon
                tableHtml += `<td>
                    <span class="rank-editable-value">${item.value || 'N/A'}</span>
                    <span class="rank-edit-icon dashicons dashicons-edit" data-post-id="${item.post_id || ''}" data-type="${category}" data-issue-type="${item.issue_type || category}"></span>
                    <span class="rank-delete-icon dashicons dashicons-trash" data-post-id="${item.post_id || ''}" data-type="${category}" data-issue-type="${item.issue_type || category}"></span>
                </td>`;
            }
            tableHtml += '</tr>';
        });

        tableHtml += '</tbody></table>';
        $tableContainer.html(staticMessage + searchHtml + tableHtml);
        
        // Add event handlers after the table is added to the DOM
        // Use .off() first to prevent duplicate handlers when paginating
        $tableContainer.off('click', '.rank-edit-icon').on('click', '.rank-edit-icon', handleEditClick);
        $tableContainer.off('click', '.rank-delete-icon').on('click', '.rank-delete-icon', handleDeleteClick);
        
        // Add search event handlers
        addSearchEventHandlers($tableContainer, category, $tableContainer.closest('.rank-accordion-item'));
    }
    
    // Function to handle edit icon clicks
    function handleEditClick() {
        const $icon = $(this);
        const $cell = $icon.parent();
        const $valueSpan = $cell.find('.rank-editable-value');
        const currentValue = $valueSpan.text();
        const isOption = $icon.data('is-option') === true;
        const category = $icon.data('type');
        const oldUrl = isOption ? decodeURIComponent($icon.data('old-url')) : '';
        const postId = $icon.data('post-id');
        const objectId = $icon.data('object-id');
        
        // Hide the current content and icon
        $valueSpan.hide();
        $icon.hide();
        
        // Add edit field and buttons
        $cell.append(`
            <div class="rank-edit-container">
                <input type="text" class="rank-edit-input" value="${currentValue}" style="width: 100%; margin-bottom: 5px;">
                <button class="rank-save-btn button button-small">Save</button>
                <button class="rank-cancel-btn button button-small">Cancel</button>
            </div>
        `);
        
        // Focus the input field
        $cell.find('.rank-edit-input').focus();
        
        // Handle save button click
        $cell.find('.rank-save-btn').on('click', function() {
            const $btn = $(this);
            const $input = $cell.find('.rank-edit-input');
            const newValue = $input.val();
            
            // Show loading indicator
            $btn.text('Saving...').prop('disabled', true);
            $cell.find('.rank-cancel-btn').prop('disabled', true);
            
            // AJAX call to save the new value
            $.ajax({
                url: rank_ajax_obj.ajax_url,
                type: 'POST',
                data: {
                    action: 'rank_update_fix_value',
                    nonce: rank_ajax_obj.nonce,
                    category: category,
                    value: newValue,
                    is_option: isOption,
                    old_url: oldUrl,
                    post_id: postId,
                    object_id: objectId,
                    issue_type: $icon.data('issue-type') || category
                },
                success: function(response) {
                    if (response.success) {
                        // Update the displayed value
                        $valueSpan.text(newValue).show();
                        $icon.show();
                        $cell.find('.rank-edit-container').remove();
                    } else {
                        alert('Error updating value: ' + (response.data || 'Unknown error'));
                        // Restore the edit field
                        $btn.text('Save').prop('disabled', false);
                        $cell.find('.rank-cancel-btn').prop('disabled', false);
                    }
                },
                error: function() {
                    alert('AJAX error occurred while updating value');
                    // Restore the edit field
                    $btn.text('Save').prop('disabled', false);
                    $cell.find('.rank-cancel-btn').prop('disabled', false);
                }
            });
        });
        
        // Handle cancel button click
        $cell.find('.rank-cancel-btn').on('click', function() {
            // Restore the original display
            $valueSpan.show();
            $icon.show();
            $cell.find('.rank-edit-container').remove();
        });
    }
    
    // Function to handle delete icon clicks
    function handleDeleteClick() {
        const $icon = $(this);
        const $cell = $icon.parent();
        const $row = $cell.parent();
        const isOption = $icon.data('is-option') === true;
        const category = $icon.data('type');
        const oldUrl = isOption ? decodeURIComponent($icon.data('old-url')) : '';
        const postId = $icon.data('post-id');
        const objectId = $icon.data('object-id');
        const issueType = $icon.data('issue-type') || category;
        
        // Create and show confirmation dialog
        const $confirmDialog = $(`
            <div class="rank-confirm-delete-dialog" style="position: absolute; background: white; border: 1px solid #ddd; border-radius: 4px; padding: 10px; box-shadow: 0 2px 5px rgba(0,0,0,0.2); z-index: 100;">
                <p>Are you sure you want to delete this item?</p>
                <div style="text-align: right;">
                    <button class="rank-confirm-delete-btn button button-small button-primary">Delete</button>
                    <button class="rank-cancel-delete-btn button button-small">Cancel</button>
                </div>
            </div>
        `);
        
        // Position the dialog near the delete icon
        $cell.css('position', 'relative');
        $cell.append($confirmDialog);
        
        // Handle confirm button click
        $confirmDialog.find('.rank-confirm-delete-btn').on('click', function() {
            const $btn = $(this);
            
            // Disable buttons during AJAX call
            $btn.text('Deleting...').prop('disabled', true);
            $confirmDialog.find('.rank-cancel-delete-btn').prop('disabled', true);
            
            // AJAX call to delete the item
            $.ajax({
                url: rank_ajax_obj.ajax_url,
                type: 'POST',
                data: {
                    action: 'rank_delete_fix_item',
                    nonce: rank_ajax_obj.nonce,
                    category: category,
                    is_option: isOption,
                    old_url: oldUrl,
                    post_id: postId,
                    object_id: objectId,
                    issue_type: issueType
                },
                success: function(response) {
                    if (response.success) {
                        // Remove the row from the table
                        $row.fadeOut(300, function() {
                            $(this).remove();
                            
                            // Update count in header
                            const $header = $row.closest('.rank-accordion-item').find('.rank-accordion-header');
                            const $countSpan = $header.find('.rank-accordion-count');
                            const currentCount = parseInt($countSpan.text().replace('✅ ', ''));
                            if (!isNaN(currentCount) && currentCount > 0) {
                                $countSpan.text(`✅ ${currentCount - 1}`);
                            }
                            
                            // Show notice if successful
                            if (rank.helpers && rank.helpers.showNotice) {
                                rank.helpers.showNotice('Item deleted successfully.', 'success');
                            }
                        });
                    } else {
                        // Show error message
                        alert('Error deleting item: ' + (response.data || 'Unknown error'));
                        $confirmDialog.remove();
                    }
                },
                error: function() {
                    alert('AJAX error occurred while deleting item');
                    $confirmDialog.remove();
                }
            });
        });
        
        // Handle cancel button click
        $confirmDialog.find('.rank-cancel-delete-btn').on('click', function() {
            $confirmDialog.remove();
        });
        
        // Close dialog when clicking outside
        $(document).on('click.rank-delete-dialog', function(e) {
            if (!$(e.target).closest('.rank-confirm-delete-dialog, .rank-delete-icon').length) {
                $confirmDialog.remove();
                $(document).off('click.rank-delete-dialog');
            }
        });
    }

    // Function to add search event handlers
    function addSearchEventHandlers($container, category, $item) {
        // Search button click
        $container.on('click', '.rank-search-btn', function() {
            const searchQuery = $(this).siblings('.rank-search-input').val().trim();
            if (searchQuery) {
                // Show clear button when search is performed
                $(this).siblings('.rank-clear-search-btn').show();
            }
            performSearch(category, searchQuery, $item);
        });
        
        // Clear search button click
        $container.on('click', '.rank-clear-search-btn', function() {
            $(this).siblings('.rank-search-input').val('');
            // Hide clear button when search is cleared
            $(this).hide();
            performSearch(category, '', $item);
        });
        
        // Enter key support
        $container.on('keypress', '.rank-search-input', function(e) {
            if (e.which === 13) {
                const searchQuery = $(this).val().trim();
                if (searchQuery) {
                    // Show clear button when search is performed
                    $(this).siblings('.rank-clear-search-btn').show();
                }
                performSearch(category, searchQuery, $item);
            }
        });
        
        // Restore previous search query if it exists
        const currentSearch = $item.data('current-search') || '';
        if (currentSearch) {
            $container.find('.rank-search-input').val(currentSearch);
            $container.find('.rank-clear-search-btn').show();
            updateSearchResultsInfo($container, currentSearch);
        }
    }
    
    // Function to perform search
    function performSearch(category, searchQuery, $item) {
        // Store search state
        $item.data('current-search', searchQuery);
        
        // Reset to page 1 for new search
        loadFixesData(category, 1, $item, searchQuery);
    }
    
    // Function to update search results info
    function updateSearchResultsInfo($container, searchQuery) {
        const $info = $container.find('.rank-search-results-info');
        if (searchQuery) {
            $info.text(`Searching for: "${searchQuery}"`).show();
        } else {
            $info.hide();
        }
    }

    // Function to display pagination controls
    function displayPagination(data, $paginationContainer, category, $item) {
        $paginationContainer.empty(); // Clear existing controls

        const $paginationControls = $('<div class="rank-pagination-controls" style="display: flex; justify-content: space-between; align-items: center; gap: 20px;"></div>');

        // Get current per_page from stored data
        const currentPerPage = $item.data('per-page') || data.per_page || 20;
        const currentSearch = $item.data('current-search') || '';

        // Per page selector (for right side)
        const $perPageLabel = $('<label for="rank-per-page-select" style="margin-right: 5px;">' + (rank_ajax_obj.text_show || 'Show') + ':</label>');
        const $perPageSelect = $(`<select id="rank-per-page-select" class="rank-per-page-select">`);
        const perPageOptions = [10, 20, 50, 100];
        perPageOptions.forEach(option => {
            const $option = $('<option></option>').val(option).text(option);
            if (option === currentPerPage) {
                $option.prop('selected', true);
            }
            $perPageSelect.append($option);
        });

        // Info Text (e.g., "Page 1 of 5 (85 items)")
        const $paginationInfo = $('<span class="rank-pagination-info"></span>');
        if (data.total_pages > 0) {
            const firstItem = (data.current_page - 1) * data.per_page + 1;
            const lastItem = Math.min(data.current_page * data.per_page, data.total_items);
            $paginationInfo.text(
                `${firstItem}-${lastItem} ${rank_ajax_obj.text_of || 'of'} ${data.total_items} ${rank_ajax_obj.text_items || 'items'}`
            );
        } else {
            $paginationInfo.text(`0 ${rank_ajax_obj.text_items || 'items'}`);
        }

        // Right side: Per page selector and page info
        const $topRow = $('<div class="rank-pagination-top" style="display: flex; align-items: center; gap: 10px;"></div>');
        $topRow.append($perPageLabel);
        $topRow.append($perPageSelect);
        $topRow.append($paginationInfo);

        // Left side: Page navigation
        const $bottomRow = $('<div class="rank-pagination-bottom" style="display: flex; align-items: center; gap: 5px;"></div>');
        if (data.total_pages > 1) {
            // Previous Button
            const $prevButton = $(`<button type="button" class="button button-small rank-prev-page" ${data.current_page === 1 ? 'disabled' : ''}>${rank_ajax_obj.text_prev || 'Previous'}</button>`);

            // Page input field
            const $pageInputLabel = $('<label for="rank-page-input" style="margin: 0 5px;">' + (rank_ajax_obj.text_page || 'Page') + ':</label>');
            const $pageInput = $('<input type="number" id="rank-page-input" class="rank-page-input" min="1" max="' + data.total_pages + '" value="' + data.current_page + '">');
            const $pageInputInfo = $('<span style="margin: 0 5px;">' + (rank_ajax_obj.text_of || 'of') + ' ' + data.total_pages + '</span>');

            // Next Button
            const $nextButton = $(`<button type="button" class="button button-small rank-next-page" ${data.current_page === data.total_pages ? 'disabled' : ''}>${rank_ajax_obj.text_next || 'Next'}</button>`);

            $bottomRow.append($prevButton);
            $bottomRow.append($pageInputLabel);
            $bottomRow.append($pageInput);
            $bottomRow.append($pageInputInfo);
            $bottomRow.append($nextButton);

            // Attach click handlers
            $prevButton.on('click', function() {
                if (data.current_page > 1) {
                    loadFixesData(category, data.current_page - 1, $item, currentSearch, currentPerPage);
                }
            });

            $nextButton.on('click', function() {
                if (data.current_page < data.total_pages) {
                    loadFixesData(category, data.current_page + 1, $item, currentSearch, currentPerPage);
                }
            });

            // Page input handlers
            $pageInput.on('keypress', function(e) {
                if (e.which === 13) { // Enter key
                    e.preventDefault();
                    const newPage = parseInt($(this).val(), 10);
                    if (newPage >= 1 && newPage <= data.total_pages) {
                        loadFixesData(category, newPage, $item, currentSearch, currentPerPage);
                    } else {
                        // Reset to current page if invalid
                        $(this).val(data.current_page);
                        alert((rank_ajax_obj.text_invalid_page || 'Invalid page number.') + ' ' + (rank_ajax_obj.text_enter_page_between || 'Please enter a page number between') + ' 1 ' + (rank_ajax_obj.text_and || 'and') + ' ' + data.total_pages + '.');
                    }
                }
            });

            $pageInput.on('blur', function() {
                const newPage = parseInt($(this).val(), 10);
                if (newPage < 1 || newPage > data.total_pages || isNaN(newPage)) {
                    // Reset to current page if invalid
                    $(this).val(data.current_page);
                }
            });
        }

        // Per page change handler (always needed)
        $perPageSelect.on('change', function() {
            const newPerPage = parseInt($(this).val(), 10);
            $item.data('per-page', newPerPage);
            // Reset to page 1 when changing per page
            loadFixesData(category, 1, $item, currentSearch, newPerPage);
        });

        // Build pagination controls - bottom row (left), top row (right)
        if (data.total_pages > 1) {
            $paginationControls.append($bottomRow);
        }
        $paginationControls.append($topRow);

        $paginationContainer.append($paginationControls);
    }

    // Initialize - Load fix counts on page load
    $(document).ready(function() {
        // Subtab switching (same pattern as Rank Booster)
        $('.rank-booster-subtab').on('click', function() {
            var tab = $(this).data('subtab');
            $('.rank-booster-subtab').removeClass('active');
            $(this).addClass('active');
            $('.rank-booster-subtab-content').hide();
            $('#rank-booster-' + tab).show();
        });

        // Auto-activate subtab if specified in URL (e.g. ?subtab=fixes-view)
        var urlParams = new URLSearchParams(window.location.search);
        var requestedSubtab = urlParams.get('subtab');
        if (requestedSubtab) {
            $('.rank-booster-subtab[data-subtab="' + requestedSubtab + '"]').trigger('click');
        }

        loadInitialFixCounts();
        
        // Add notice box below accordion tables
        if ($fixesAccordion.length) {
            $fixesAccordion.after(
                '<div class="rank-notice-box" style="width: 175px;padding: 10px;background-color: #f8f8f8;border: 1px solid #ddd;border-radius: 4px;text-align: center;position: static;margin-top: 100px;">' +
                '<a href="https://morningscore.io/automatic-seo-wordpress-plugin-rank-ai/#lwptoc10" target="_blank" style="color: #0073aa; text-decoration: none;">❓️ Does a fix not work?</a>' +
                '</div>'
            );
            
            // Add CSS for the delete icon
            $('head').append(`
                <style>
                    .rank-delete-icon {
                        color: #d63638;
                        margin-left: 5px;
                        cursor: pointer;
                    }
                    .rank-delete-icon:hover {
                        color: #b32d2e;
                    }
                    .rank-confirm-delete-dialog {
                        min-width: 200px;
                    }
                    .rank-confirm-delete-btn {
                        margin-left: 5px !important;
                    }
                </style>
            `);
        }
    });
    
    // Export functions to rank object for potential use in other modules
    rank.fixesOverview = {
        loadInitialFixCounts: loadInitialFixCounts,
        loadFixesData: loadFixesData,
        displayFixesData: displayFixesData,
        displayPagination: displayPagination,
        handleEditClick: handleEditClick,
        handleDeleteClick: handleDeleteClick,
        addSearchEventHandlers: addSearchEventHandlers,
        performSearch: performSearch,
        updateSearchResultsInfo: updateSearchResultsInfo
    };

})(jQuery, window.rank = window.rank || {});