/**
 * Groups Modal - Display lists within a group
 * WP Mailinglist Plugin
 * Security: HTML escaping to prevent XSS
 */

(function ($) {
    'use strict';

    // Security: HTML escape function
    function escapeHtml(text) {
        var map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return String(text).replace(/[&<>"']/g, function (m) { return map[m]; });
    }

    // Initialize on document ready
    $(document).ready(function () {
        // Handle click on group list count
        $(document).on('click', '.newsletters-group-lists-link', function (e) {
            e.preventDefault();

            // Security: Sanitize data attributes
            var groupId = parseInt($(this).data('group-id'), 10);
            var groupTitle = $(this).data('group-title');

            if (!groupId || isNaN(groupId)) {
                return false;
            }

            // Show loading modal
            showGroupListsModal(groupId, groupTitle);

            return false;
        });
    });

    /**
     * Show modal with group lists
     */
    function showGroupListsModal(groupId, groupTitle) {
        // Security: Escape HTML to prevent XSS
        var escapedTitle = escapeHtml(groupTitle);
        var escapedViewingText = escapeHtml(newsletters_groups_modal.viewing_lists);
        var escapedLoadingText = escapeHtml(newsletters_groups_modal.loading);

        // Create modal content
        var modalContent = '<div id="newsletters-group-modal" style="padding: 20px;">' +
            '<h2>' + escapedViewingText + ' ' + escapedTitle + '</h2>' +
            '<div id="newsletters-group-modal-content">' +
            '<p><i class="fa-solid fa-arrows-rotate fa-spin"></i> ' + escapedLoadingText + '</p>' +
            '</div>' +
            '</div>';

        // Show modal using jQuery colorbox with increased height
        $.colorbox({
            html: modalContent,
            width: '600px',
            height: '600px', // Increased from auto to 600px
            maxHeight: '80%',
            onComplete: function () {
                // Load lists via AJAX
                loadGroupLists(groupId);
            }
        });
    }

    /**
     * Load lists for a group via AJAX
     */
    function loadGroupLists(groupId) {
        // Security: Validate groupId is numeric
        if (!groupId || isNaN(groupId)) {
            $('#newsletters-group-modal-content').html(
                '<p class="newsletters_error">' + escapeHtml(newsletters_groups_modal.error) + '</p>'
            );
            return;
        }

        $.ajax({
            url: newsletters_ajaxurl + 'action=newsletters_get_group_lists&security=' + newsletters_groups_modal.nonce,
            type: 'POST',
            data: {
                group_id: parseInt(groupId, 10) // Security: Ensure integer
            },
            success: function (response) {
                if (response.success && response.data.lists) {
                    displayGroupLists(response.data.lists);
                } else {
                    var errorMsg = response.data && response.data.message ? response.data.message : newsletters_groups_modal.error;
                    $('#newsletters-group-modal-content').html(
                        '<p class="newsletters_error">' + escapeHtml(errorMsg) + '</p>'
                    );
                }
            },
            error: function () {
                $('#newsletters-group-modal-content').html(
                    '<p class="newsletters_error">' + escapeHtml(newsletters_groups_modal.error) + '</p>'
                );
            }
        });
    }

    /**
     * Display lists in modal
     * Security: All output is HTML escaped
     */
    function displayGroupLists(lists) {
        if (!lists || lists.length === 0) {
            $('#newsletters-group-modal-content').html(
                '<p>' + escapeHtml(newsletters_groups_modal.no_lists) + '</p>'
            );
            return;
        }

        var html = '<table class="widefat" style="margin-top: 15px;">' +
            '<thead>' +
            '<tr>' +
            '<th>' + escapeHtml(newsletters_groups_modal.list_name) + '</th>' +
            '<th>' + escapeHtml(newsletters_groups_modal.subscribers) + '</th>' +
            '</tr>' +
            '</thead>' +
            '<tbody>';

        $.each(lists, function (index, list) {
            var rowClass = (index % 2 === 0) ? '' : 'alternate';
            // Security: Escape all output
            html += '<tr class="' + escapeHtml(rowClass) + '">' +
                '<td><strong>' + escapeHtml(list.title) + '</strong></td>' +
                '<td>' + parseInt(list.subscriber_count, 10) + ' ' + escapeHtml(newsletters_groups_modal.active) + '</td>' +
                '</tr>';
        });

        html += '</tbody></table>';

        $('#newsletters-group-modal-content').html(html);
    }

})(jQuery);
