/**
 * Profile Navigation JavaScript
 * Handles navigation functionality for user profile blocks
 */

(function($) {
    'use strict';

    // Global functions for profile navigation
    window.wpufProfileGoBack = function() {
        // First check if we have dir_page parameter - if yes, use that directly
        var currentUrl = new URL(window.location.href);
        var dirPage = currentUrl.searchParams.get('dir_page');

        // If we have dir_page, skip referrer and build the URL directly
        if (!dirPage && document.referrer && document.referrer.includes(window.location.hostname)) {
            // Try to use browser history first to preserve pagination and other parameters
            var referrerUrl = new URL(document.referrer);

            // Check if referrer is the directory page (without the user segment)
            var referrerPath = referrerUrl.pathname.replace(/\/+$/, '');
            var currentPath = currentUrl.pathname.replace(/\/[^\/]+\/?$/, '').replace(/\/+$/, '');

            // Check if referrer looks like a directory page
            // It should either match the current path base, or contain /page/
            if (referrerPath === currentPath ||
                referrerPath.includes('/page/') ||
                referrerUrl.searchParams.has('page') ||
                referrerUrl.searchParams.has('orderby') ||
                referrerUrl.searchParams.has('order') ||
                referrerUrl.searchParams.has('search')) {

                // Remove tab and activity-related parameters from referrer URL
                referrerUrl.searchParams.delete('tab');
                referrerUrl.searchParams.delete('cpage');
                window.location.href = referrerUrl.toString();
                return;
            }
        }

        // Fallback: construct directory URL preserving directory parameters
        var currentUrl = window.location.href;
        var url = new URL(currentUrl);

        // Check for dir_page parameter to restore directory pagination
        var dirPage = url.searchParams.get('dir_page');

        // Save directory-related parameters
        var preserveParams = {};
        ['orderby', 'order', 'search', 'filter'].forEach(function(param) {
            if (url.searchParams.has(param)) {
                preserveParams[param] = url.searchParams.get(param);
            }
        });

        // Remove ALL query parameters first
        url.search = '';

        // Get the base directory path by removing user identifier
        // For URLs like /new-user-directory/admin/, we want /new-user-directory/
        var pathParts = url.pathname.split('/').filter(part => part !== '');

        // Remove the last segment if it exists (user identifier)
        if (pathParts.length > 0) {
            pathParts.pop();
        }

        // Rebuild the base directory path
        url.pathname = '/' + pathParts.join('/') + '/';

        // If we have a dir_page parameter, add it to the path for clean URL pagination
        if (dirPage && dirPage > 1) {
            url.pathname = url.pathname.replace(/\/$/, '') + '/page/' + dirPage + '/';
        }

        // Re-add preserved directory parameters
        Object.keys(preserveParams).forEach(function(param) {
            url.searchParams.set(param, preserveParams[param]);
        });

        // Navigate to directory listing with preserved parameters
        window.location.href = url.toString();
    };

    window.wpufProfileEditMode = function() {
        // Check if we have the account page URL from localized data
        if (typeof wpufUserDirectory !== 'undefined' && wpufUserDirectory.account_page_url) {
            window.location.href = wpufUserDirectory.account_page_url;
        } else {
            // Fallback: try to find account page
            const accountPageUrl = wpufFindAccountPage();
            if (accountPageUrl) {
                window.location.href = accountPageUrl;
            } else {
                // Show error message
                alert('Edit profile page not found. Please contact the administrator.');
            }
        }
    };

    // Helper function to find account page
    function wpufFindAccountPage() {
        // Try to find account page by common slugs
        const commonSlugs = ['account', 'profile', 'edit-profile', 'my-account', 'user-account'];

        for (let slug of commonSlugs) {
            const url = window.location.origin + '/' + slug;
            // Note: This is a basic check, in a real implementation you might want to
            // make an AJAX call to verify the page exists
            return url;
        }

        return null;
    }

    // Initialize when DOM is ready
    $(document).ready(function() {
        // Add click handlers for navigation buttons
        $(document).on('click', '.wpuf-nav-button.wpuf-back-button', function(e) {
            e.preventDefault();
            wpufProfileGoBack();
        });

        $(document).on('click', '.wpuf-nav-button.wpuf-edit-button', function(e) {
            e.preventDefault();
            wpufProfileEditMode();
        });

        // Add keyboard navigation support
        $(document).on('keydown', function(e) {
            // Escape key to go back
            if (e.key === 'Escape') {
                wpufProfileGoBack();
            }
        });
    });

})(jQuery);
