/**
 * 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 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 HTML from the counts element (preserves color spans)
            const countsHtml = rank.elements.counts.html();
            
            // Clear the counts element
            rank.elements.counts.empty();
            
            // Add the HTML and button directly next to each other
            rank.elements.counts.html(countsHtml);
            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, source, title) {
        source = source || 'issues';

        // 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 class="rank-modal-title">Full list of pages to Fix</h3>
                    <p class="rank-modal-skip"><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();
                }
            });
        }

        // Set the title and toggle the "skip" help link depending on which list we show
        const defaultTitle = source === 'already_fixed'
            ? 'Pages detected as already fixed'
            : (source === 'unsupported' ? 'Unsupported pages' : 'Full list of pages to Fix');
        $modal.find('.rank-modal-title').text(title || defaultTitle);
        // The "skip pages" help link only makes sense for pages still to fix
        $modal.find('.rank-modal-skip').toggle(source === 'issues');
        
        // Show modal and load first page
        $modal.show();
        loadUrlsPage(batchId, issueType, 1, source);
    }
    
    /**
     * 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, source) {
        source = source || 'issues';
        const $urlsList = $('#rank-urls-modal .rank-urls-list');
        const $pagination = $('#rank-urls-modal .rank-pagination');
        // Fetch the total first (page 1) so we can size perPage to fit
        // everything on a single page. The modal is short enough that
        // pagination would just be noise — and a too-small perPage (e.g. 20)
        // would silently truncate the list.
        const perPage = 9999; // upper bound; server caps at 200 but we ask for "all"

        // 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,
                source: source
            },
            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, source, response.data.detail_column);

                    // Only show pagination if the server actually split the
                    // result into multiple pages (i.e. > 200 items, the
                    // server's hard cap).
                    if (response.data.total_pages > 1) {
                        updatePagination($pagination, page, response.data.total_pages, function(newPage) {
                            loadUrlsPage(batchId, issueType, newPage, source);
                        });
                    } else {
                        $pagination.empty();
                    }
                } 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, source, detailColumn) {
        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>${detailColumn ? `<th>${escapeHtml(detailColumn.label)}</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
            // The Image URL column explains *why* a page appears multiple times
            // (different large images on the same page, or the same image on
            // many pages for large_images / image_alt issues). Empty cell when
            // the issue type doesn't carry an image (e.g. meta descriptions).
            const detailValue = item.detail || '';
            let detailCell = '<span style="color: #999;">—</span>';
            if (detailValue) {
                const escapedDetail = escapeHtml(detailValue);
                detailCell = detailColumn && detailColumn.format === 'url'
                    ? `<a href="${escapedDetail}" target="_blank" style="word-break: break-all; font-size: 12px;">${escapedDetail}</a>`
                    : escapedDetail;
            }

            // For grouped image rows (one entry per unique image with a
            // page_urls[] list), show the first page as the primary link and
            // a "+ N more pages" details/summary listing the rest. Mirrors
            // the Fixes tab UX so the user understands why a page URL
            // appears multiple times across batches.
            let urlCell = `<a href="${item.url}" target="_blank">${item.url}</a>`;
            if (item.is_group && Array.isArray(item.page_urls) && item.page_urls.length > 1) {
                const more = item.page_urls.slice(1);
                urlCell += `<details class="rank-page-list-details" style="margin-top: 4px;">
                    <summary style="cursor: pointer; color: #0073aa; display: inline-block; list-style: none; padding: 2px 6px; background: #f0f6fc; border: 1px solid #b6d8fb; border-radius: 3px; font-size: 11px; line-height: 1;">+ ${more.length} more page${more.length === 1 ? '' : 's'}</summary>
                    <ul style="margin: 6px 0 0 0; padding-left: 18px; font-size: 12px;">${more.map(u => {
                        const rel = (u || '').replace(/^https?:\/\/[^\/]+/, '') || '/';
                        return `<li style="margin: 2px 0;"><a href="javascript:void(0);" onclick="window.open('${u}','_blank');" style="word-break: break-all;">${rel}</a></li>`;
                    }).join('')}</ul>
                </details>`;
            }

            html += `<tr>
                <td>${startIndex + index + 1}</td>
                <td>${urlCell}</td>
                ${detailColumn ? `<td>${detailCell}</td>` : ''}
            </tr>`;
        });
        
        html += '</tbody></table>';
        $container.html(html);
    }

    function escapeHtml(value) {
        return $('<div>').text(value).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: 90%;
                max-width: 1100px;
                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;
                table-layout: fixed;
            }

            .rank-urls-table th:nth-child(1),
            .rank-urls-table td:nth-child(1) {
                width: 50px;
            }
            .rank-urls-table th:nth-child(2),
            .rank-urls-table td:nth-child(2) {
                word-break: break-all;
            }
            .rank-urls-table th:nth-child(3),
            .rank-urls-table td:nth-child(3) {
                word-break: break-all;
                font-size: 12px;
                color: #555;
            }

            .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);