/**
 * 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);
            }
        });
    }

    // Accordion Header Click
    $fixesAccordion.on('click', '.rank-accordion-header', function() {
        const $header = $(this);
        const $content = $header.next('.rank-accordion-content');
        const $item = $header.closest('.rank-accordion-item');
        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 = '') {
        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;

        $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
            },
            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="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
        $tableContainer.on('click', '.rank-edit-icon', handleEditClick);
        $tableContainer.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();
            performSearch(category, searchQuery, $item);
        });
        
        // Clear search button click
        $container.on('click', '.rank-clear-search-btn', function() {
            $(this).siblings('.rank-search-input').val('');
            performSearch(category, '', $item);
        });
        
        // Enter key support
        $container.on('keypress', '.rank-search-input', function(e) {
            if (e.which === 13) {
                const searchQuery = $(this).val().trim();
                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);
            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

        if (data.total_pages <= 1) {
            return; // No pagination needed if 1 page or less
        }

        const $paginationInfo = $('<span class="rank-pagination-info"></span>');
        const $paginationControls = $('<div class="rank-pagination-controls"></div>');

        // Info Text (e.g., "Page 1 of 5 (85 items)")
        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(
            `${rank_ajax_obj.text_page || 'Page'} ${data.current_page} ${rank_ajax_obj.text_of || 'of'} ${data.total_pages} (${firstItem}-${lastItem} ${rank_ajax_obj.text_of || 'of'} ${data.total_items} ${rank_ajax_obj.text_items || 'items'})`
        );

        // 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>`);

        // 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>`);

        // Build pagination controls
        $paginationControls.append($prevButton);
        $paginationControls.append($paginationInfo);
        $paginationControls.append($nextButton);

        // Get current search query to maintain state
        const currentSearch = $item.data('current-search') || '';
        
        // Attach click handlers
        $prevButton.on('click', function() {
            if (data.current_page > 1) {
                loadFixesData(category, data.current_page - 1, $item, currentSearch);
            }
        });

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

        $paginationContainer.append($paginationControls);
    }

    // Initialize - Load fix counts on page load
    $(document).ready(function() {
        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 || {});