/**
 * URL List Modal Module
 * Handles displaying a modal with paginated URLs from health issues
 */
(function($, rankLocalizedData) {
    'use strict';
    
    /**
     * Initialize the module
     */
    function init() {
        // Add CSS for the modal
        addModalStyles();
    }
    
    /**
     * Add the "View URLs" button after issue preparation
     * @param {string} batchId The batch ID
     * @param {string} issueType The issue type
     */
    function addViewUrlsButton(batchId, issueType) {
        // Create a "View URLs" button styled as a blue link
        const $viewUrlsButton = $('<a>', {
            href: '#',
            class: 'rank-view-urls-link',
            text: 'View all pages',
            style: 'margin-left: 10px; color: #0073aa; text-decoration: none; font-size: 14px;'
        }).on('click', function(e) {
            e.preventDefault();
            showUrlsModal(batchId, issueType);
        });
        
        // Add the button inline with the text in the counts element
        if (rank.elements.counts && rank.elements.counts.length) {
            // First remove any existing button
            $('.rank-view-urls-link').remove();
            
            // Get the current text from the counts element
            const countsText = rank.elements.counts.text();
            
            // Clear the counts element
            rank.elements.counts.empty();
            
            // Add the text and button directly next to each other
            rank.elements.counts.append(document.createTextNode(countsText));
            rank.elements.counts.append($viewUrlsButton);
        }
    }
    
    /**
     * Show the modal with URLs
     * @param {string} batchId The batch ID
     * @param {string} issueType The issue type
     */
    function showUrlsModal(batchId, issueType) {
        // Create modal container if it doesn't exist
        let $modal = $('#rank-urls-modal');
        if ($modal.length === 0) {
            $modal = $('<div>', {
                id: 'rank-urls-modal',
                class: 'rank-modal'
            }).appendTo('body');
            
            // Add modal content structure
            $modal.html(`
                <div class="rank-modal-content">
                    <span class="rank-modal-close">&times;</span>
                    <h3>Full list of pages to Fix</h3>
                    <p><a href="https://help.morningscore.io/en/article/how-to-make-the-tool-ignore-health-issues-oyh8cj/" target="_blank" style="font-weight: bold;">⏭️ Skip pages from this list</a></p>
                    <div class="rank-urls-list"></div>
                    <div class="rank-pagination"></div>
                </div>
            `);
            
            // Close button functionality
            $modal.find('.rank-modal-close').on('click', function() {
                $modal.hide();
            });
            
            // Close when clicking outside the modal
            $(window).on('click', function(event) {
                if ($(event.target).is($modal)) {
                    $modal.hide();
                }
            });
        }
        
        // Show modal and load first page
        $modal.show();
        loadUrlsPage(batchId, issueType, 1);
    }
    
    /**
     * Load a page of URLs
     * @param {string} batchId The batch ID
     * @param {string} issueType The issue type
     * @param {number} page The page number to load
     */
    function loadUrlsPage(batchId, issueType, page) {
        const $urlsList = $('#rank-urls-modal .rank-urls-list');
        const $pagination = $('#rank-urls-modal .rank-pagination');
        const perPage = 200; // Items per page
        
        // Show loading
        $urlsList.html('<p><span class="spinner is-active"></span> Loading URLs...</p>');
        
        // Make AJAX request to get URLs for this page
        $.ajax({
            url: rankLocalizedData.ajax_url,
            type: 'POST',
            data: {
                action: 'rank_get_issue_urls',
                nonce: rankLocalizedData.nonce,
                batch_id: batchId,
                page: page,
                per_page: perPage
            },
            success: function(response) {
                if (response.success && response.data) {
                    // Display URLs with page and perPage information for correct numbering
                    displayUrls($urlsList, response.data.urls, page, perPage);
                    
                    // Update pagination
                    updatePagination($pagination, page, response.data.total_pages, function(newPage) {
                        loadUrlsPage(batchId, issueType, newPage);
                    });
                } else {
                    $urlsList.html('<p>Error loading URLs: ' + (response.data.message || 'Unknown error') + '</p>');
                }
            },
            error: function() {
                $urlsList.html('<p>Error loading URLs. Please try again.</p>');
            }
        });
    }
    
    /**
     * Display URLs in the container
     * @param {jQuery} $container The container element
     * @param {Array} urls The URLs to display
     */
    function displayUrls($container, urls, page, perPage) {
        if (!urls || urls.length === 0) {
            $container.html('<p>No URLs found.</p>');
            return;
        }
        
        let html = '<table class="rank-urls-table">';
        html += '<thead><tr><th>#</th><th>URL</th></tr></thead><tbody>';
        
        // Calculate the starting index based on the current page
        const startIndex = (page - 1) * perPage;
        
        urls.forEach((item, index) => {
            // Display the full URL instead of just the title or basename
            // Use startIndex + index + 1 to continue numbering from previous pages
            html += `<tr>
                <td>${startIndex + index + 1}</td>
                <td><a href="${item.url}" target="_blank">${item.url}</a></td>
            </tr>`;
        });
        
        html += '</tbody></table>';
        $container.html(html);
    }
    
    /**
     * Update pagination controls
     * @param {jQuery} $container The pagination container
     * @param {number} currentPage The current page
     * @param {number} totalPages The total number of pages
     * @param {Function} callback The callback function when a page is clicked
     */
    function updatePagination($container, currentPage, totalPages, callback) {
        if (totalPages <= 1) {
            $container.empty();
            return;
        }
        
        let html = '<div class="rank-pagination-controls">';
        
        // Previous button
        if (currentPage > 1) {
            html += `<button class="button" data-page="${currentPage - 1}">« Previous</button>`;
        } else {
            html += `<button class="button" disabled>« Previous</button>`;
        }
        
        // Page info
        html += `<span class="rank-pagination-info">Page ${currentPage} of ${totalPages}</span>`;
        
        // Next button
        if (currentPage < totalPages) {
            html += `<button class="button" data-page="${currentPage + 1}">Next »</button>`;
        } else {
            html += `<button class="button" disabled>Next »</button>`;
        }
        
        html += '</div>';
        $container.html(html);
        
        // Add click handlers
        $container.find('button[data-page]').on('click', function() {
            const page = parseInt($(this).data('page'));
            callback(page);
        });
    }
    
    /**
     * Add CSS styles for the modal
     */
    function addModalStyles() {
        const styles = `
            .rank-modal {
                display: none;
                position: fixed;
                z-index: 100000;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                overflow: auto;
                background-color: rgba(0, 0, 0, 0.4);
            }
            
            .rank-modal-content {
                background-color: #fefefe;
                margin: 5% auto;
                padding: 20px;
                border: 1px solid #888;
                width: 80%;
                max-width: 800px;
                max-height: 80vh;
                overflow-y: auto;
            }
            
            .rank-modal-close {
                color: #aaa;
                float: right;
                font-size: 28px;
                font-weight: bold;
                cursor: pointer;
            }
            
            .rank-modal-close:hover,
            .rank-modal-close:focus {
                color: black;
                text-decoration: none;
                cursor: pointer;
            }
            
            .rank-urls-table {
                width: 100%;
                border-collapse: collapse;
                margin-top: 10px;
            }
            
            .rank-urls-table th,
            .rank-urls-table td {
                padding: 8px;
                text-align: left;
                border-bottom: 1px solid #ddd;
            }
            
            .rank-pagination-controls {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-top: 20px;
            }
            
            .rank-pagination-info {
                text-align: center;
            }
        `;
        
        $('<style>').text(styles).appendTo('head');
    }
    
    /**
     * Remove the "View URLs" button
     */
    function removeViewUrlsButton() {
        // Remove any existing button
        $('.rank-view-urls-link').remove();
    }
    
    // Expose public methods
    rank.urlListModal = {
        init: init,
        addViewUrlsButton: addViewUrlsButton,
        removeViewUrlsButton: removeViewUrlsButton,
        showUrlsModal: showUrlsModal
    };
    
})(jQuery, window.rankLocalizedData);