// user-directory-search.js
// Global search manager for all user directory layouts
// @since 4.2.0

(function(window, document) {
    const SEARCH_DEBOUNCE = 300;
    let debounceTimeout = null;

    function fetchUsers({
        blockId = '',
        pageId = '',
        directoryId = '',
        layout = '',
        search = '',
        page = 1,
        orderby = '',
        order = '',
        roles = '',
        exclude_roles = '',
        exclude_users = '',
        search_by = '',
        avatar_size = '', // Add avatar_size parameter
        max_item_per_page = '10', // Add max_item_per_page parameter
        users_per_row = '3', // Add users_per_row parameter
        onSuccess = () => {},
        onError = () => {},
        apiUrl = '/wp-json/wpuf/v1/user_directory/search',
    }) {
        const params = new URLSearchParams();
        if (blockId) params.append('block_id', blockId);
        if (pageId) params.append('page_id', pageId);
        if (directoryId) params.append('directory_id', directoryId);
        if (layout) params.append('directory_layout', layout);
        if (search) params.append('search', search);
        if (page && page > 1) params.append('page', page);
        if (orderby) params.append('orderby', orderby);
        if (order) params.append('order', order);
        if (roles && roles !== 'all') params.append('roles', roles);
        if (exclude_roles) params.append('exclude_roles', exclude_roles);
        if (exclude_users) params.append('exclude_users', exclude_users);
        if (search_by) params.append('search_by', search_by);
        if (avatar_size) params.append('avatar_size', avatar_size); // Pass avatar_size for legacy support
        if (max_item_per_page) params.append('max_item_per_page', max_item_per_page); // Pass max items per page
        if (users_per_row) params.append('users_per_row', users_per_row); // Pass users per row
        // Send the full page URL where the block is rendered for simple profile URL generation
        // Remove pagination parameters like /page/1, /page/2, etc. from the pathname
        // Handle all pagination patterns: /page/2, /page/2/, etc.
        const cleanPathname = window.location.pathname.replace(/\/page\/\d+\/?$/, '');
        const fullPageUrl = window.location.origin + cleanPathname;
        params.append('base_url', fullPageUrl);

        const finalUrl = apiUrl + '?' + params.toString();

        fetch(finalUrl, {
            credentials: 'same-origin',
        })
            .then(res => res.json())
            .then(data => {
                if (data && data.success) {
                    onSuccess(data);
                } else {
                    onError(data);
                }
            })
            .catch(onError);
    }

    function initUserDirectorySearch(container, blockId, pageId) {
        // select the div with `wpuf-user-listing` class and `data-block-id` attribute === blockId
        const listingDiv = document.querySelector('.wpuf-user-listing[data-block-id="' + blockId + '"]');
        const input = listingDiv ? listingDiv.querySelector('.wpuf-ud-search-input') : null;
        // Support both table layout (.wpuf-ud-tbody) and list layout (ul[role="list"])
        let userList = listingDiv ? (
            listingDiv.querySelector('.wpuf-ud-tbody') ||
            listingDiv.querySelector('ul[role="list"]')
        ) : null;

        const pagination = listingDiv ? listingDiv.querySelector('.wpuf-ud-pagination') : null;
        const liveRegion = listingDiv ? listingDiv.querySelector('[aria-live]') : null;

        // Get sorting dropdowns and controls
        const sortBySelect = listingDiv ? listingDiv.querySelector('.wpuf-ud-sort-by') : null;
        const sortOrderSelect = listingDiv ? listingDiv.querySelector('.wpuf-ud-sort-order') : null;
        const searchBySelect = listingDiv ? listingDiv.querySelector('.wpuf-ud-search-in') : null;
        const resetButton = listingDiv ? listingDiv.querySelector('.wpuf-ud-reset-filters') : null;

        // Get layout information from DOM
        const layout = listingDiv ? listingDiv.dataset.layout || '' : '';

        // Get directory ID from data attribute
        const directoryId = listingDiv ? listingDiv.dataset.directoryId || '' : '';

        // Get block settings from data attributes
        const roles = listingDiv ? listingDiv.dataset.roles || '' : '';
        const excludeRoles = listingDiv ? listingDiv.dataset.excludeRoles || '' : '';
        const excludeUsers = listingDiv ? listingDiv.dataset.excludeUsers || '' : '';
        const maxItemPerPage = listingDiv ? listingDiv.dataset.maxItemPerPage || '10' : '10';

        // Get avatar size from data attribute (for legacy support)
        const avatarSize = listingDiv ? listingDiv.dataset.avatarSize || '' : '';

        // Get avatar settings from data attributes for table layout
        const showAvatar = listingDiv ? listingDiv.dataset.showAvatar !== 'false' : true;
        const avatarShape = listingDiv ? listingDiv.dataset.avatarShape || 'circle' : 'circle';
        const avatarFallbackType = listingDiv ? listingDiv.dataset.avatarFallbackType || 'initial' : 'initial';

        // Get users per row from data attribute
        const usersPerRow = listingDiv ? listingDiv.dataset.usersPerRow || '3' : '3';

        if (!input || !userList) return;

        // Store original grid structure at initialization for layout-4 and layout-7
        // This ensures we can restore the exact structure after search/sort operations
        if (!listingDiv.dataset.originalGridClasses) {
            const listContainer = listingDiv.querySelector('.wpuf-ud-list');
            if (listContainer) {
                const gridElement = listContainer.querySelector('ul[role="list"]');
                if (gridElement) {
                    // Store the original classes
                    listingDiv.dataset.originalGridClasses = gridElement.className;
                }
            }
        }

        // Function to show loading state
        function showLoading() {
            // Add loading class to container
            if (listingDiv) {
                listingDiv.classList.add('wpuf-ud-loading');
            }

            // Show loading overlay if user list exists
            if (userList) {
                // Create or show loading overlay
                let loadingOverlay = listingDiv.querySelector('.wpuf-ud-loading-overlay');
                if (!loadingOverlay) {
                    loadingOverlay = document.createElement('div');
                    loadingOverlay.className = 'wpuf-ud-loading-overlay';
                    loadingOverlay.style.cssText = `
                        position: absolute;
                        top: 0;
                        left: 0;
                        right: 0;
                        bottom: 0;
                        background: rgba(255, 255, 255, 0.8);
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        z-index: 10;
                    `;

                    const spinner = document.createElement('div');
                    spinner.className = 'wpuf-ud-spinner';
                    spinner.style.cssText = `
                        width: 40px;
                        height: 40px;
                        border: 4px solid #f3f3f3;
                        border-top: 4px solid #3498db;
                        border-radius: 50%;
                        animation: wpuf-spin 1s linear infinite;
                    `;

                    loadingOverlay.appendChild(spinner);

                    // Add CSS animation if not already present
                    if (!document.querySelector('#wpuf-spinner-styles')) {
                        const style = document.createElement('style');
                        style.id = 'wpuf-spinner-styles';
                        style.textContent = `
                            @keyframes wpuf-spin {
                                0% { transform: rotate(0deg); }
                                100% { transform: rotate(360deg); }
                            }
                        `;
                        document.head.appendChild(style);
                    }

                    // Position relative to userList container
                    const listContainer = userList.closest('.wpuf-ud-list, .wpuf-table-responsive');
                    if (listContainer) {
                        listContainer.style.position = 'relative';
                        listContainer.appendChild(loadingOverlay);
                    }
                } else {
                    loadingOverlay.style.display = 'flex';
                }
            }
        }

        // Function to hide loading state
        function hideLoading() {
            // Remove loading class from container
            if (listingDiv) {
                listingDiv.classList.remove('wpuf-ud-loading');
            }

            // Hide loading overlay
            const loadingOverlay = listingDiv ? listingDiv.querySelector('.wpuf-ud-loading-overlay') : null;
            if (loadingOverlay) {
                loadingOverlay.style.display = 'none';
            }
        }

        // Function to perform search/pagination request
        function performSearch(searchTerm, page = 1) {
            // Get current sorting values
            const currentOrderby = sortBySelect ? sortBySelect.value : '';
            const currentOrder = sortOrderSelect ? sortOrderSelect.value : '';

            // Get selected search field
            const searchByField = searchBySelect ? searchBySelect.value : '';

            // Show loading state
            showLoading();

            fetchUsers({
                blockId,
                pageId,
                directoryId,
                layout,
                search: searchTerm,
                page: page,
                orderby: currentOrderby,
                order: currentOrder,
                roles: roles,
                exclude_roles: excludeRoles,
                exclude_users: excludeUsers,
                search_by: searchByField,
                avatar_size: avatarSize, // Pass avatar size for legacy support
                show_avatar: showAvatar, // Pass show avatar setting for table layout
                avatar_shape: avatarShape, // Pass avatar shape for table layout
                avatar_fallback_type: avatarFallbackType, // Pass avatar fallback type for table layout
                max_item_per_page: maxItemPerPage, // Pass max items per page
                users_per_row: usersPerRow, // Pass users per row
                onSuccess: (data) => {
                    // Hide loading state
                    hideLoading();

                    try {
                        // Use container_html if available (new block-based approach)
                        if (data.container_html && data.container_html.trim() !== '') {
                            // Simple container replacement - no more nested element manipulation
                            const listContainer = listingDiv.querySelector('.wpuf-user-list-container');
                            if (listContainer) {
                                listContainer.innerHTML = data.container_html;
                                // Update userList reference for future operations
                                userList = listContainer.querySelector('.wpuf-ud-tbody, ul[role="list"]');
                            }
                        } else if (data.full_html && data.full_html.trim() !== '') {
                            // Fallback to full_html for backward compatibility
                            const listContainer = listingDiv.querySelector('.wpuf-ud-list');
                            if (listContainer) {
                                listContainer.innerHTML = data.full_html;
                            }
                        } else if (data.rows_html && data.rows_html.trim() !== '') {
                            // Fallback to rows_html for legacy support
                            const listContainer = listingDiv.querySelector('.wpuf-ud-list');
                            if (listContainer) {
                                const tbody = listContainer.querySelector('.wpuf-ud-tbody');
                                if (tbody) {
                                    tbody.innerHTML = data.rows_html;
                                } else {
                                    let currentUserList = listContainer.querySelector('ul[role="list"]');
                                    if (currentUserList) {
                                        currentUserList.innerHTML = data.rows_html;
                                    }
                                }
                            }
                        } else {
                            // Handle no users found case based on usercount
                            if (!data.usercount || data.usercount === 0) {
                            // Check if API provided full_html for list layouts (complete container replacement)
                            if (data.full_html && data.full_html.trim() !== '') {
                                // API provided a complete container replacement for list layouts
                                const listContainer = listingDiv.querySelector('.wpuf-ud-list');
                                if (listContainer) {
                                    // Replace the entire content with the no-users design
                                    listContainer.innerHTML = data.full_html;
                                }
                            } else if (data.rows_html && data.rows_html.trim() !== '') {
                                // API provided layout-appropriate empty content, use it directly
                                // This handles table layouts (<tr><td>) that still use rows_html
                                if (userList) {
                                    userList.innerHTML = data.rows_html;
                                }
                            } else {
                                // API didn't provide rows_html, fallback to generic message
                        // Store original HTML structure for restoration
                        if (!listingDiv.dataset.originalStructure) {
                            const listContainer = listingDiv.querySelector('.wpuf-ud-list');
                            if (listContainer && userList) {
                                // Store the current structure without user data
                                const tempContainer = listContainer.cloneNode(true);
                                const tempUserList = tempContainer.querySelector('.wpuf-ud-tbody, ul[role="list"]');
                                if (tempUserList) {
                                    tempUserList.innerHTML = '';
                                }
                                listingDiv.dataset.originalStructure = tempContainer.innerHTML;
                            }
                        }

                        // Clear the user list
                        if (userList) {
                            userList.innerHTML = '';
                        }

                        // Create or update no results message
                        let noResultsContainer = listingDiv.querySelector('.wpuf-no-users-container');
                        if (!noResultsContainer) {
                            // Create the container
                            noResultsContainer = document.createElement('div');
                            noResultsContainer.className = 'wpuf-no-users-container wpuf-flex wpuf-items-center wpuf-justify-center wpuf-min-h-[400px]';
                            noResultsContainer.style.cssText = `
                                display: flex;
                                align-items: center;
                                justify-content: center;
                                min-height: 400px;
                            `;

                            // Create the inner content wrapper
                            const noResultsContent = document.createElement('div');
                            noResultsContent.className = 'wpuf-no-users-found wpuf-flex wpuf-flex-col wpuf-items-center wpuf-justify-center wpuf-text-center';
                            noResultsContent.style.cssText = `
                                display: flex;
                                flex-direction: column;
                                align-items: center;
                                justify-content: center;
                                text-align: center;
                            `;

                            // Create icon container
                            const iconContainer = document.createElement('div');
                            iconContainer.className = 'wpuf-bg-gray-100 wpuf-rounded-full wpuf-p-4 wpuf-mb-4';
                            iconContainer.style.cssText = `
                                background-color: #f3f4f6;
                                border-radius: 50%;
                                padding: 1rem;
                                margin-bottom: 1rem;
                            `;

                            // Create SVG icon
                            const svgIcon = `
                                <svg class="wpuf-w-12 wpuf-h-12 wpuf-text-gray-400" style="width: 3rem; height: 3rem; color: #9ca3af;" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                                </svg>
                            `;
                            iconContainer.innerHTML = svgIcon;

                            // Create heading
                            const heading = document.createElement('h3');
                            heading.className = 'wpuf-text-base wpuf-font-semibold wpuf-text-gray-900 wpuf-mb-2';
                            heading.style.cssText = `
                                font-size: 1rem;
                                font-weight: 600;
                                color: #111827;
                                margin-bottom: 0.5rem;
                            `;
                            heading.textContent = 'No users found matching your search criteria.';

                            // Create description
                            const description = document.createElement('p');
                            description.className = 'wpuf-text-sm wpuf-text-gray-500';
                            description.style.cssText = `
                                font-size: 0.875rem;
                                color: #6b7280;
                            `;
                            description.textContent = 'Try adjusting your search or filter to find what you\'re looking for.';

                            // Assemble the structure
                            noResultsContent.appendChild(iconContainer);
                            noResultsContent.appendChild(heading);
                            noResultsContent.appendChild(description);
                            noResultsContainer.appendChild(noResultsContent);

                            // Insert in the main list container
                            const listContainer = listingDiv.querySelector('.wpuf-ud-list');
                            if (listContainer) {
                                // Clear and replace content
                                listContainer.innerHTML = '';
                                listContainer.appendChild(noResultsContainer);
                            }
                        }
                        noResultsContainer.style.display = 'flex';
                            }
                    } else {
                        // Users found - update content
                        const listContainer = listingDiv.querySelector('.wpuf-ud-list');

                        // Remove no results container if exists
                        const noResultsContainer = listingDiv.querySelector('.wpuf-no-users-container');
                        if (noResultsContainer) {
                            noResultsContainer.remove();
                        }

                        // For table layouts, update tbody content
                        const tbody = listContainer.querySelector('.wpuf-ud-tbody');

                        if (tbody) {
                            tbody.innerHTML = data.rows_html;
                        } else {
                            // For list layouts, update ul content
                            let currentUserList = listContainer.querySelector('ul[role="list"]');

                            if (!currentUserList) {
                                // Create list structure if it doesn't exist
                                if (data.full_html) {
                                    listContainer.innerHTML = data.full_html;
                                } else {
                                    // Get layout from the listing div
                                    const currentLayout = listingDiv.dataset.layout || '';

                                    // Set layout-specific grid classes and structure
                                    let gridClasses = '';
                                    let htmlStructure = '';

                                    switch(currentLayout) {
                                        case 'layout-2':
                                            // Layout-2 classes (user-lists templates removed)
                                            gridClasses = '!wpuf-mx-auto !wpuf-mt-4 !wpuf-grid !wpuf-grid-cols-1 md:!wpuf-grid-cols-2 !wpuf-gap-6 !wpuf-max-w-none !wpuf-justify-items-center';
                                            htmlStructure = `<ul role="list" class="${gridClasses}"></ul>`;
                                            break;
                                        case 'layout-3':
                                            // Layout-3 classes (user-lists templates removed)
                                            gridClasses = '!wpuf-mx-auto !wpuf-grid !wpuf-max-w-2xl !wpuf-grid-cols-1 !wpuf-gap-x-6 !wpuf-gap-y-6 sm:!wpuf-grid-cols-2 lg:!wpuf-mx-0 lg:!wpuf-max-w-none lg:!wpuf-grid-cols-3';
                                            htmlStructure = `<div><ul role="list" class="${gridClasses}"></ul></div>`;
                                            break;
                                        case 'layout-4':
                                            // Use stored original classes if available, otherwise use defaults
                                            if (listingDiv.dataset.originalGridClasses) {
                                                gridClasses = listingDiv.dataset.originalGridClasses;
                                            } else {
                                                // Layout-4 classes (user-lists templates removed)
                                                gridClasses = '!wpuf-mx-auto !wpuf-grid !wpuf-max-w-2xl !wpuf-grid-cols-1 !wpuf-gap-x-6 !wpuf-gap-y-6 sm:!wpuf-grid-cols-2 lg:!wpuf-mx-0 lg:!wpuf-max-w-none lg:!wpuf-grid-cols-3';
                                            }
                                            htmlStructure = `<div><ul role="list" class="${gridClasses}"></ul></div>`;
                                            break;
                                        case 'layout-5':
                                            // Layout-5 classes (user-lists templates removed)
                                            gridClasses = 'wpuf-mx-auto wpuf-grid wpuf-max-w-2xl wpuf-grid-cols-1 wpuf-gap-x-6 wpuf-gap-y-6 sm:wpuf-grid-cols-2 lg:wpuf-mx-0 lg:wpuf-max-w-none lg:wpuf-grid-cols-4';
                                            htmlStructure = `<div><ul role="list" class="${gridClasses}"></ul></div>`;
                                            break;
                                        case 'layout-6':
                                            // Layout-6 classes (user-lists templates removed)
                                            gridClasses = 'wpuf-mx-auto wpuf-mt-4 wpuf-grid wpuf-max-w-2xl wpuf-grid-cols-1 wpuf-gap-x-6 wpuf-gap-y-20 sm:wpuf-grid-cols-2 lg:wpuf-max-w-4xl lg:wpuf-gap-x-8 xl:wpuf-max-w-none';
                                            htmlStructure = `<ul role="list" class="${gridClasses}"></ul>`;
                                            break;
                                        case 'layout-7':
                                            // Layout-7 classes (2-column grid based on layout-4)
                                            if (listingDiv.dataset.originalGridClasses) {
                                                gridClasses = listingDiv.dataset.originalGridClasses;
                                            } else {
                                                gridClasses = '!wpuf-mx-auto !wpuf-grid !wpuf-max-w-2xl !wpuf-grid-cols-1 !wpuf-gap-x-6 !wpuf-gap-y-6 sm:!wpuf-grid-cols-2 lg:!wpuf-mx-0 lg:!wpuf-max-w-none lg:!wpuf-grid-cols-2';
                                            }
                                            htmlStructure = `<div><ul role="list" class="${gridClasses}"></ul></div>`;
                                            break;
                                        case 'layout-8':
                                            // Layout-8 classes (3-column grid based on layout-2)
                                            gridClasses = 'wpuf-mx-auto wpuf-mt-4 wpuf-grid wpuf-grid-cols-1 md:wpuf-grid-cols-2 lg:wpuf-grid-cols-3 wpuf-gap-6 wpuf-max-w-none wpuf-justify-items-center';
                                            htmlStructure = `<ul role="list" class="${gridClasses}"></ul>`;
                                            break;
                                        case 'layout-9':
                                            // Layout-9 classes (3-column grid, same as layout-8)
                                            gridClasses = 'wpuf-mx-auto wpuf-mt-4 wpuf-grid wpuf-grid-cols-1 md:wpuf-grid-cols-2 lg:wpuf-grid-cols-3 wpuf-gap-6 wpuf-max-w-none wpuf-justify-items-center';
                                            htmlStructure = `<ul role="list" class="${gridClasses}"></ul>`;
                                            break;
                                        case 'layout-10':
                                            // Layout-10 classes (2-column grid, Wide Sidecard based on layout-2)
                                            gridClasses = 'wpuf-mx-auto wpuf-mt-4 wpuf-grid wpuf-grid-cols-1 md:wpuf-grid-cols-2 wpuf-gap-6 wpuf-max-w-none wpuf-justify-items-center';
                                            htmlStructure = `<ul role="list" class="${gridClasses}"></ul>`;
                                            break;
                                        default:
                                            // Default fallback for unknown layouts
                                            gridClasses = '!wpuf-mx-auto !wpuf-grid !wpuf-max-w-2xl !wpuf-grid-cols-1 !wpuf-gap-x-6 !wpuf-gap-y-6 sm:!wpuf-grid-cols-2 lg:!wpuf-mx-0 lg:!wpuf-max-w-none lg:!wpuf-grid-cols-3';
                                            htmlStructure = `<ul role="list" class="${gridClasses}"></ul>`;
                                    }

                                    listContainer.innerHTML = htmlStructure;
                                }
                                currentUserList = listContainer.querySelector('ul[role="list"]');
                            }

                            // Update the content
                            if (currentUserList) {
                                currentUserList.innerHTML = data.rows_html;
                            }
                        }

                        // Update userList reference for future use
                        userList = listContainer.querySelector('.wpuf-ud-tbody, ul[role="list"]');
                            }
                        }

                    if (data.pagination_html && pagination) {
                        pagination.innerHTML = data.pagination_html;
                        // Re-attach pagination event listeners after updating HTML
                        attachPaginationListeners();
                    } else if (pagination) {
                        // Clear pagination if no pagination HTML (e.g., single page)
                        pagination.innerHTML = '';
                    }
                    if (liveRegion && data.announce) liveRegion.textContent = data.announce;

                    // Update browser URL to reflect current state (optional, for bookmarking)
                    const url = new URL(window.location);

                    // Handle search parameter
                    if (searchTerm) {
                        url.searchParams.set('search', searchTerm);
                    } else {
                        url.searchParams.delete('search');
                    }

                    // Handle sorting parameters
                    if (currentOrderby) {
                        url.searchParams.set('orderby', currentOrderby);
                    } else {
                        url.searchParams.delete('orderby');
                    }

                    if (currentOrder) {
                        url.searchParams.set('order', currentOrder);
                    } else {
                        url.searchParams.delete('order');
                    }

                    // Handle pagination - preserve pretty permalink structure if it exists
                    const currentPath = url.pathname;
                    const hasPrettyPagination = /\/page\/\d+\/?$/.test(currentPath);

                    if (page > 1) {
                        if (hasPrettyPagination || currentPath.endsWith('/')) {
                            // Use pretty permalink format
                            // Remove existing pagination and trailing slash, then add new pagination
                            const basePath = currentPath.replace(/\/page\/\d+\/?$/, '').replace(/\/$/, '');
                            url.pathname = basePath + '/page/' + page + '/';
                            url.searchParams.delete('page'); // Remove query param if it exists
                        } else {
                            // Use query parameter format
                            url.searchParams.set('page', page);
                        }
                    } else {
                        if (hasPrettyPagination) {
                            // Remove pretty pagination from path, ensure single trailing slash
                            const basePath = currentPath.replace(/\/page\/\d+\/?$/, '').replace(/\/$/, '');
                            url.pathname = basePath + '/';
                        }
                        url.searchParams.delete('page');
                    }

                    window.history.replaceState({}, '', url);

                    const event = new CustomEvent('wpuf:ud:search:results', { detail: data });
                    container.dispatchEvent(event);
                    } catch (error) {
                        // Silently handle errors in onSuccess callback
                    }
                },
                onError: (err) => {
                    // Hide loading state
                    hideLoading();

                    // AJAX Error handling
                    if (liveRegion) liveRegion.textContent = 'Search failed.';
                    const event = new CustomEvent('wpuf:ud:search:error', { detail: err });
                    container.dispatchEvent(event);
                }
            });
        }

        // Function to attach pagination event listeners
        function attachPaginationListeners() {
            if (!pagination) return;

            // Only target links with the pagination-specific class
            const paginationLinks = pagination.querySelectorAll('a.wpuf-pagination-link');

            paginationLinks.forEach(link => {
                link.addEventListener('click', function(e) {
                    e.preventDefault();

                    // Skip if this is a disabled link
                    const href = this.getAttribute('href');
                    if (href === '#' || this.getAttribute('aria-disabled') === 'true') {
                        return;
                    }

                    // Extract page number from href
                    const url = new URL(href, window.location.origin);

                    // Handle both pretty permalinks (/page/2/) and query params (?page=2)
                    let page = url.searchParams.get('page');
                    if (!page) {
                        // Try to extract from pretty permalink format /page/X/
                        const pathMatch = url.pathname.match(/\/page\/(\d+)\/?$/);
                        page = pathMatch ? pathMatch[1] : 1;
                    }
                    page = page || 1;

                    // Get current search term
                    const currentSearch = input.value.trim();

                    // Preserve orderby and order from the clicked link's URL if they exist
                    const orderby = url.searchParams.get('orderby');
                    const order = url.searchParams.get('order');

                    // Update sort dropdowns if parameters exist in URL
                    if (orderby && sortBySelect) {
                        sortBySelect.value = orderby;
                    }
                    if (order && sortOrderSelect) {
                        sortOrderSelect.value = order;
                    }

                    // Perform search with pagination
                    performSearch(currentSearch, parseInt(page));
                });
            });
        }

        // Search input handler
        input.addEventListener('input', function(e) {
            const value = e.target.value.trim();
            if (debounceTimeout) clearTimeout(debounceTimeout);
            debounceTimeout = setTimeout(() => {
                // Reset to page 1 when searching
                performSearch(value, 1);
            }, SEARCH_DEBOUNCE);
        });

        // Sort by dropdown handler
        if (sortBySelect) {
            sortBySelect.addEventListener('change', function() {
                const currentSearch = input.value.trim();
                // Reset to page 1 when sorting
                performSearch(currentSearch, 1);
            });
        }

        // Sort order dropdown handler
        if (sortOrderSelect) {
            sortOrderSelect.addEventListener('change', function() {
                const currentSearch = input.value.trim();
                // Reset to page 1 when sorting
                performSearch(currentSearch, 1);
            });
        }

        // Search by dropdown handler
        if (searchBySelect) {
            searchBySelect.addEventListener('change', function() {
                const currentSearch = input.value.trim();
                // Only perform search if there's a search term
                if (currentSearch) {
                    // Reset to page 1 when changing search field
                    performSearch(currentSearch, 1);
                }
            });
        }

        // Reset filters button handler
        if (resetButton) {
            resetButton.addEventListener('click', function(e) {
                e.preventDefault();

                // Clear search input
                input.value = '';

                // Reset sort dropdowns to default values
                if (sortBySelect) {
                    sortBySelect.value = '';
                }
                if (sortOrderSelect) {
                    sortOrderSelect.value = '';
                }
                if (searchBySelect) {
                    searchBySelect.value = '';
                }

                // Perform search with empty values to show all users
                performSearch('', 1);
            });
        }

        // Initialize pagination listeners on page load
        attachPaginationListeners();

        // Initialize search field from URL parameters (for direct links)
        const urlParams = new URLSearchParams(window.location.search);
        const initialSearch = urlParams.get('search');
        const initialOrderby = urlParams.get('orderby');
        const initialOrder = urlParams.get('order');

        if (initialSearch && input.value !== initialSearch) {
            input.value = initialSearch;
        }

        // Initialize sorting dropdowns from URL parameters
        // Only override the default values if URL parameters are present
        if (initialOrderby && sortBySelect) {
            sortBySelect.value = initialOrderby;
        } else if (sortBySelect && !sortBySelect.value) {
            // If no URL parameter and no value is selected, keep the pre-selected value from PHP
            // The value should already be set by PHP's selected() function
        }

        if (initialOrder && sortOrderSelect) {
            sortOrderSelect.value = initialOrder;
        } else if (sortOrderSelect && !sortOrderSelect.value) {
            // If no URL parameter and no value is selected, keep the pre-selected value from PHP
            // The value should already be set by PHP's selected() function
        }

        // Get initial page from URL (handle both pretty permalinks and query params)
        let initialPage = 1;
        const pathMatch = window.location.pathname.match(/\/page\/(\d+)/);
        if (pathMatch) {
            initialPage = parseInt(pathMatch[1]);
        } else if (urlParams.get('page')) {
            initialPage = parseInt(urlParams.get('page'));
        }

        // Trigger search if there are initial parameters OR if we're on a page > 1
        if (initialSearch || initialOrderby || initialOrder || initialPage > 1) {
            performSearch(initialSearch || '', initialPage);
        }
    }

    const listings = document.querySelectorAll('.wpuf-user-listing');

    listings.forEach(
        (listing) => {
            const blockId = listing.dataset.blockId || '';
            const pageId = listing.dataset.pageId || '';
            initUserDirectorySearch(listing, blockId, pageId);
        }
    );
})(window, document);
