/**
 * Send Post Modals - Display subscribers and role users
 * WP Mailinglist Plugin
 */

(function ($) {
    'use strict';

    var currentRequest = null;
    var searchTimeout = null;

    // Security: HTML escape function
    function escapeHtml(text) {
        if (text === null || text === undefined) {
            return '';
        }
        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 list active subscribers count
        $(document).on('click', '.newsletters-list-subscribers-link', function (e) {
            e.preventDefault();

            var listId = parseInt($(this).data('list-id'), 10);
            var listTitle = $(this).data('list-title');

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

            showSubscribersModal(listId, listTitle);
            return false;
        });

        // Handle click on role users count
        $(document).on('click', '.newsletters-role-users-link', function (e) {
            e.preventDefault();

            var role = $(this).data('role');
            var roleName = $(this).data('role-name');

            if (!role) {
                return false;
            }

            showRoleUsersModal(role, roleName);
            return false;
        });

        // Handle pagination clicks within modal
        $(document).on('click', '.newsletters-modal-pagination a', function (e) {
            e.preventDefault();
            var page = $(this).data('page');
            var type = $(this).data('type');
            var id = $(this).data('id'); // list_id or role
            var search = $('#newsletters-modal-search').val();

            if (type === 'subscribers') {
                loadListSubscribers(id, page, search);
            } else if (type === 'roles') {
                loadRoleUsers(id, page, search);
            }
        });

        // Handle search input
        $(document).on('keyup', '#newsletters-modal-search', function (e) {
            var search = $(this).val();
            var type = $(this).data('type');
            var id = $(this).data('id');

            // Clear existing timeout
            if (searchTimeout) {
                clearTimeout(searchTimeout);
            }

            // Set new timeout for debounce
            searchTimeout = setTimeout(function () {
                if (type === 'subscribers') {
                    loadListSubscribers(id, 1, search);
                } else if (type === 'roles') {
                    loadRoleUsers(id, 1, search);
                }
            }, 500); // 500ms debounce
        });
    });

    /**
     * Show modal for List Subscribers
     */
    function showSubscribersModal(listId, listTitle) {
        var escapedTitle = escapeHtml(listTitle);
        var escapedHeader = escapeHtml(newsletters_send_modals.viewing_subscribers);
        var escapedLoading = escapeHtml(newsletters_send_modals.loading);
        var escapedSearchPlaceholder = escapeHtml(newsletters_send_modals.search_placeholder);

        var modalContent = '<div id="newsletters-send-modal" style="padding: 20px;">' +
            '<h2>' + escapedHeader + ': ' + escapedTitle + '</h2>' +
            '<div class="newsletters-modal-tools" style="margin-bottom: 15px;">' +
            '<input type="text" id="newsletters-modal-search" data-type="subscribers" data-id="' + listId + '" class="widefat" placeholder="' + escapedSearchPlaceholder + '" style="max-width: 300px;">' +
            '</div>' +
            '<div id="newsletters-send-modal-content">' +
            '<p><i class="fa-solid fa-arrows-rotate fa-spin"></i> ' + escapedLoading + '</p>' +
            '</div>' +
            '</div>';

        $.colorbox({
            html: modalContent,
            width: '600px',
            height: '600px',
            maxHeight: '80%',
            onComplete: function () {
                loadListSubscribers(listId, 1, '');
            }
        });
    }

    /**
     * Show modal for Role Users
     */
    function showRoleUsersModal(role, roleName) {
        var escapedName = escapeHtml(roleName);
        var escapedHeader = escapeHtml(newsletters_send_modals.viewing_users);
        var escapedLoading = escapeHtml(newsletters_send_modals.loading);
        var escapedSearchPlaceholder = escapeHtml(newsletters_send_modals.search_users_placeholder);

        var modalContent = '<div id="newsletters-send-modal" style="padding: 20px;">' +
            '<h2>' + escapedHeader + ': ' + escapedName + '</h2>' +
            '<div class="newsletters-modal-tools" style="margin-bottom: 15px;">' +
            '<input type="text" id="newsletters-modal-search" data-type="roles" data-id="' + escapeHtml(role) + '" class="widefat" placeholder="' + escapedSearchPlaceholder + '" style="max-width: 300px;">' +
            '</div>' +
            '<div id="newsletters-send-modal-content">' +
            '<p><i class="fa-solid fa-arrows-rotate fa-spin"></i> ' + escapedLoading + '</p>' +
            '</div>' +
            '</div>';

        $.colorbox({
            html: modalContent,
            width: '600px',
            height: '600px',
            maxHeight: '80%',
            onComplete: function () {
                loadRoleUsers(role, 1, '');
            }
        });
    }

    /**
     * Load List Subscribers via AJAX
     */
    function loadListSubscribers(listId, page, search) {
        if (currentRequest) {
            currentRequest.abort();
        }

        $('#newsletters-send-modal-content').css('opacity', '0.5');

        currentRequest = $.ajax({
            url: newsletters_ajaxurl + 'action=newsletters_get_list_subscribers&security=' + newsletters_send_modals.nonce,
            type: 'POST',
            data: {
                list_id: listId,
                page: page,
                search: search
            },
            success: function (response) {
                $('#newsletters-send-modal-content').css('opacity', '1');
                if (response.success) {
                    displaySubscribers(response.data.subscribers, response.data.total_pages, page, listId);
                } else {
                    var errorMsg = response.data && response.data.message ? response.data.message : newsletters_send_modals.error;
                    $('#newsletters-send-modal-content').html(
                        '<p class="newsletters_error">' + escapeHtml(errorMsg) + '</p>'
                    );
                }
            },
            error: function (jqXHR, textStatus) {
                if (textStatus === 'abort') return;
                $('#newsletters-send-modal-content').css('opacity', '1');
                $('#newsletters-send-modal-content').html(
                    '<p class="newsletters_error">' + escapeHtml(newsletters_send_modals.error) + '</p>'
                );
            }
        });
    }

    /**
     * Load Role Users via AJAX
     */
    function loadRoleUsers(role, page, search) {
        if (currentRequest) {
            currentRequest.abort();
        }

        $('#newsletters-send-modal-content').css('opacity', '0.5');

        currentRequest = $.ajax({
            url: newsletters_ajaxurl + 'action=newsletters_get_role_users&security=' + newsletters_send_modals.nonce,
            type: 'POST',
            data: {
                role: role,
                page: page,
                search: search
            },
            success: function (response) {
                $('#newsletters-send-modal-content').css('opacity', '1');
                if (response.success) {
                    displayRoleUsers(response.data.users, response.data.total_pages, page, role);
                } else {
                    var errorMsg = response.data && response.data.message ? response.data.message : newsletters_send_modals.error;
                    $('#newsletters-send-modal-content').html(
                        '<p class="newsletters_error">' + escapeHtml(errorMsg) + '</p>'
                    );
                }
            },
            error: function (jqXHR, textStatus) {
                if (textStatus === 'abort') return;
                $('#newsletters-send-modal-content').css('opacity', '1');
                $('#newsletters-send-modal-content').html(
                    '<p class="newsletters_error">' + escapeHtml(newsletters_send_modals.error) + '</p>'
                );
            }
        });
    }

    /**
     * Display Subscribers Table
     */
    function displaySubscribers(subscribers, totalPages, currentPage, listId) {
        if (!subscribers || subscribers.length === 0) {
            $('#newsletters-send-modal-content').html(
                '<p>' + escapeHtml(newsletters_send_modals.no_results) + '</p>'
            );
            return;
        }

        var html = '<table class="widefat">' +
            '<thead>' +
            '<tr>' +
            '<th>' + escapeHtml(newsletters_send_modals.email) + '</th>' +
            '<th>' + escapeHtml(newsletters_send_modals.id) + '</th>' +
            '</tr>' +
            '</thead>' +
            '<tbody>';

        $.each(subscribers, function (index, subscriber) {
            var rowClass = (index % 2 === 0) ? '' : 'alternate';
            html += '<tr class="' + escapeHtml(rowClass) + '">' +
                '<td>' + escapeHtml(subscriber.email) + '</td>' +
                '<td>' + parseInt(subscriber.id, 10) + '</td>' +
                '</tr>';
        });

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

        // Pagination
        if (totalPages > 1) {
            html += '<div class="newsletters-modal-pagination" style="margin-top: 15px; text-align: center;">';

            if (currentPage > 1) {
                html += '<a href="#" class="button" data-page="' + (currentPage - 1) + '" data-type="subscribers" data-id="' + listId + '">&laquo; ' + escapeHtml(newsletters_send_modals.prev) + '</a> ';
            }

            html += '<span style="vertical-align: middle; margin: 0 10px;">' + escapeHtml(newsletters_send_modals.page) + ' ' + currentPage + ' ' + escapeHtml(newsletters_send_modals.of) + ' ' + totalPages + '</span>';

            if (currentPage < totalPages) {
                html += ' <a href="#" class="button" data-page="' + (currentPage + 1) + '" data-type="subscribers" data-id="' + listId + '">' + escapeHtml(newsletters_send_modals.next) + ' &raquo;</a>';
            }

            html += '</div>';
        }

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

    /**
     * Display Role Users Table
     */
    function displayRoleUsers(users, totalPages, currentPage, role) {
        if (!users || users.length === 0) {
            $('#newsletters-send-modal-content').html(
                '<p>' + escapeHtml(newsletters_send_modals.no_results) + '</p>'
            );
            return;
        }

        var html = '<table class="widefat">' +
            '<thead>' +
            '<tr>' +
            '<th>' + escapeHtml(newsletters_send_modals.username) + '</th>' +
            '<th>' + escapeHtml(newsletters_send_modals.email) + '</th>' +
            '</tr>' +
            '</thead>' +
            '<tbody>';

        $.each(users, function (index, user) {
            var rowClass = (index % 2 === 0) ? '' : 'alternate';
            html += '<tr class="' + escapeHtml(rowClass) + '">' +
                '<td>' + escapeHtml(user.display_name) + '</td>' +
                '<td>' + escapeHtml(user.user_email) + '</td>' +
                '</tr>';
        });

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

        // Pagination
        if (totalPages > 1) {
            html += '<div class="newsletters-modal-pagination" style="margin-top: 15px; text-align: center;">';

            if (currentPage > 1) {
                html += '<a href="#" class="button" data-page="' + (currentPage - 1) + '" data-type="roles" data-id="' + escapeHtml(role) + '">&laquo; ' + escapeHtml(newsletters_send_modals.prev) + '</a> ';
            }

            html += '<span style="vertical-align: middle; margin: 0 10px;">' + escapeHtml(newsletters_send_modals.page) + ' ' + currentPage + ' ' + escapeHtml(newsletters_send_modals.of) + ' ' + totalPages + '</span>';

            if (currentPage < totalPages) {
                html += ' <a href="#" class="button" data-page="' + (currentPage + 1) + '" data-type="roles" data-id="' + escapeHtml(role) + '">' + escapeHtml(newsletters_send_modals.next) + ' &raquo;</a>';
            }

            html += '</div>';
        }

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

})(jQuery);
