// user-directory-search-shortcode.js
// Search manager specifically for shortcode-based 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 = '', // Add max_item 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) params.append('max_item', max_item); // Pass max_item for shortcode pagination
        // Send the current page URL for correct pagination links
        params.append('base_url', window.location.pathname);


        fetch(apiUrl + '?' + params.toString(), {
            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) {
        // Request tracking to prevent race conditions
        let currentRequestId = 0;

        // 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-by') : 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 || '' : '';

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

        // Get max_item from data attribute for pagination consistency
        const maxItem = listingDiv ? listingDiv.dataset.maxItem || '' : '';

        if (!input || !userList) return;


        // 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) {
            // Generate unique request ID to prevent race conditions
            const requestId = ++currentRequestId;

            // 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
                max_item: maxItem, // Pass max_item for pagination consistency
                onSuccess: (data) => {
                    // Check if this response is from the latest request to prevent race conditions
                    if (requestId !== currentRequestId) {
                        // This is an outdated response, ignore it
                        return;
                    }

                    // Hide loading state
                    hideLoading();

                    try {
                        // For shortcodes, always use rows_html as the primary source
                        if (data.rows_html && data.rows_html.trim() !== '') {
                            // Use rows_html directly for shortcode layouts
                            if (userList) {
                                userList.innerHTML = data.rows_html;
                            }
                        } else {
                            // Handle no users found case based on usercount
                            if (!data.usercount || data.usercount === 0) {
                                // 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);
                                // Add class for CSS fallback
                                listContainer.classList.add('wpuf-no-users-state');
                            }
                        }
                        noResultsContainer.style.display = 'flex';
                            }
                        }

                    // Remove no results container if users are found
                    if (data.usercount && data.usercount > 0) {
                        const noResultsContainer = listingDiv.querySelector('.wpuf-no-users-container');
                        if (noResultsContainer) {
                            noResultsContainer.remove();
                        }

                        // Remove no-users state class from list container
                        const listContainer = listingDiv.querySelector('.wpuf-ud-list');
                        if (listContainer) {
                            listContainer.classList.remove('wpuf-no-users-state');
                        }

                        // Update userList reference for future use
                        userList = listingDiv.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 search_by parameter
                    if (searchByField) {
                        url.searchParams.set('search_by', searchByField);
                    } else {
                        url.searchParams.delete('search_by');
                    }

                    // 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) => {
                    // Check if this error is from the latest request
                    if (requestId !== currentRequestId) {
                        // This is an outdated request, ignore the error
                        return;
                    }

                    // 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();

                    // Extract page number from href
                    const href = this.getAttribute('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 their default values from wizard/settings
                if (sortBySelect) {
                    const defaultSortBy = sortBySelect.getAttribute('data-default-value') || '';
                    sortBySelect.value = defaultSortBy;
                }
                if (sortOrderSelect) {
                    const defaultSortOrder = sortOrderSelect.getAttribute('data-default-value') || 'desc';
                    sortOrderSelect.value = defaultSortOrder;
                }
                if (searchBySelect) {
                    searchBySelect.value = '';
                }

                // Perform search with default values to show all users with default sorting
                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');
        const initialSearchBy = urlParams.get('search_by');

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

        // Initialize search_by dropdown from URL parameter
        if (initialSearchBy && searchBySelect) {
            searchBySelect.value = initialSearchBy;
        }

        // Initialize sorting dropdowns from URL parameters
        // Only override the default values if URL parameters are present
        if (initialOrderby && sortBySelect) {
            sortBySelect.value = initialOrderby;
        }
        // No need to set default value here as it's already set by PHP's selected() function

        if (initialOrder && sortOrderSelect) {
            sortOrderSelect.value = initialOrder;
        }
        // No need to set default value here as it's already set by PHP's selected() function

        // Check if we're coming back from a profile page (using browser back)
        const isComingFromProfile = document.referrer &&
                                   document.referrer.includes(window.location.hostname) &&
                                   (document.referrer.includes('/user/') ||
                                    document.referrer.includes('/id/') ||
                                    /\/[^\/]+\/?$/.test(new URL(document.referrer).pathname));

        // Get initial page from URL (might be in path like /page/2/ or query like ?page=2)
        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, but skip if coming back from profile
        // to preserve the existing page state
        if (!isComingFromProfile && (initialSearch || initialOrderby || initialOrder || initialSearchBy)) {
            performSearch(initialSearch || '', initialPage);
        }
    }

    // Only initialize for shortcode listings
    const listings = document.querySelectorAll('.wpuf-user-listing');

    listings.forEach(
        (listing) => {
            const blockId = listing.dataset.blockId || '';
            const pageId = listing.dataset.pageId || '';

            // Only initialize if this is a shortcode (not a block)
            if (blockId && blockId.startsWith('shortcode_')) {
                initUserDirectorySearch(listing, blockId, pageId);
            }
        }
    );
})(window, document);
