<?php
/**
 * User Profile Layout 1 - Modern Design
 *
 * @since 4.2.0
 *
 * Available variables:
 * @var array $template_data Complete data including user info and settings
 * @var array $user User data array
 */

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Get centralized profile data
$profile_data = wpuf_ud_get_profile_data( $template_data['user'], $template_data, 'layout-1' );
$user = $profile_data['user'];
$config = $profile_data['template_config'];
$user_meta = $profile_data['user_meta'];
$contact_info = $profile_data['contact_info'];
$social_media = $profile_data['social_media'];
$navigation = $profile_data['navigation'];
$tab_config = $profile_data['tab_config'];

// Legacy variables for backward compatibility
$show_avatar = $config['show_avatar'];
$enable_tabs = $config['enable_tabs'];
$default_tabs = $config['default_tabs'];
$default_active_tab = $config['default_active_tab'];
$avatar_size = $config['avatar_size'];
$custom_tab_labels = $config['custom_tab_labels'];

?>

<!-- Main Profile Container -->
<div class="wpuf-profile-layout-1 !wpuf-min-h-screen !wpuf-py-8">
    <!-- Back Button -->
    <div class="!wpuf-mb-8">
        <button onclick="wpuf_ud_goBack()" class="wpuf-back-button !wpuf-inline-flex !wpuf-items-center !wpuf-px-4 !wpuf-py-2 !wpuf-text-sm !wpuf-font-medium !wpuf-text-gray-600 !wpuf-bg-white !wpuf-border !wpuf-border-gray-300 !wpuf-rounded-lg hover:!wpuf-bg-gray-50 hover:!wpuf-text-gray-900 !wpuf-transition-colors !wpuf-shadow-sm">
            <svg class="!wpuf-w-4 !wpuf-h-4 !wpuf-mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"/>
            </svg>
            <?php esc_html_e( 'Back to Directory', 'wpuf-pro' ); ?>
        </button>
    </div>

        <div class="!wpuf-grid !wpuf-grid-cols-1 lg:!wpuf-grid-cols-12 !wpuf-gap-8">

            <!-- Left Sidebar -->
            <div class="lg:!wpuf-col-span-4 xl:!wpuf-col-span-3 !wpuf-m-3">
                <div class="!wpuf-bg-transparent !wpuf-rounded-lg !wpuf-overflow-hidden !wpuf-sticky !wpuf-top-8">
                    <!-- User Header -->
                    <div class="!wpuf-text-left">
                        <?php if ( $show_avatar ) : ?>
                            <div class="!wpuf-w-32 !wpuf-h-32 !wpuf-mb-4 !wpuf-rounded-full !wpuf-overflow-hidden !wpuf-border-4 !wpuf-border-white">
                                <?php
                                $size = 128;
                                include WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/user-avatar.php';
                                ?>
                            </div>
                        <?php endif; ?>

                        <h1 class="!wpuf-text-xl !wpuf-font-bold !wpuf-text-gray-900 !wpuf-mb-2">
                            <?php echo esc_html( $user_meta['display_name'] ); ?>
                        </h1>

                        <!-- Contact Info -->
                        <div class="!wpuf-space-y-2 !wpuf-text-left">

                            <?php foreach ( $contact_info as $contact_key => $contact_item ) : ?>
                                <div class="!wpuf-flex !wpuf-items-center !wpuf-text-sm !wpuf-text-gray-700 !wpuf-gap-1">
                                    <?php echo $contact_item['icon']; ?>
                                    <?php if ( $contact_key === 'website' ) : ?>
                                        <a href="<?php echo esc_url( $contact_item['value'] ); ?>" target="_blank" class="!wpuf-text-gray-700 !wpuf-no-underline hover:!wpuf-underline">
                                            <?php echo esc_html( $contact_item['display_value'] ); ?>
                                        </a>
                                    <?php endif; ?>

                                    <?php if ( $contact_key === 'email' && ! empty( $contact_item['value'] ) ) : ?>
                                        <a href="mailto:<?php echo antispambot( esc_attr( $contact_item['value'] ) ); ?>" class="!wpuf-text-gray-700 !wpuf-no-underline hover:!wpuf-underline">
                                            <?php echo antispambot( esc_html( $contact_item['display_value'] ) ); ?>
                                        </a>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <!-- Action Buttons -->
                        <div class="!wpuf-mt-6 !wpuf-space-y-4">
                            <?php if ( $navigation['is_own_profile'] && $navigation['edit_profile_link'] ) : ?>
                                <a href="<?php echo esc_url( $navigation['edit_profile_link'] ); ?>" class="!wpuf-w-full !wpuf-px-4 !wpuf-py-3 !wpuf-bg-gray-800 !wpuf-text-white !wpuf-text-sm !wpuf-font-normal !wpuf-rounded-lg !wpuf-border !wpuf-border-gray-300 hover:!wpuf-bg-gray-700 !wpuf-transition-colors !wpuf-duration-200 !wpuf-flex !wpuf-items-center !wpuf-justify-between !wpuf-no-underline">
                                    <span><?php esc_html_e( 'Edit Profile', 'wpuf-pro' ); ?></span>
                                    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" class="!wpuf-w-5 !wpuf-h-5">
                                        <path d="M13.5858 3.58579C14.3668 2.80474 15.6332 2.80474 16.4142 3.58579C17.1953 4.36683 17.1953 5.63316 16.4142 6.41421L15.6213 7.20711L12.7929 4.37868L13.5858 3.58579Z" fill="white"/>
                                        <path d="M11.3787 5.79289L3 14.1716V17H5.82842L14.2071 8.62132L11.3787 5.79289Z" fill="white"/>
                                    </svg>
                                </a>
                            <?php endif; ?>

                            <?php if ( $navigation['can_message'] && $navigation['message_link'] ) : ?>
                                <a href="<?php echo esc_url( $navigation['message_link'] ); ?>" target="_blank" class="!wpuf-w-full !wpuf-px-4 !wpuf-py-3 !wpuf-bg-gray-800 !wpuf-text-white !wpuf-text-sm !wpuf-font-normal !wpuf-rounded-lg !wpuf-border !wpuf-border-gray-300 hover:!wpuf-bg-gray-700 !wpuf-transition-colors !wpuf-duration-200 !wpuf-flex !wpuf-items-center !wpuf-justify-between !wpuf-no-underline">
                                    <span><?php esc_html_e( 'Message', 'wpuf-pro' ); ?></span>
                                    <svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg" class="!wpuf-w-5 !wpuf-h-5">
                                        <path d="M8.625 10.1602C8.625 10.3673 8.45711 10.5352 8.25 10.5352C8.04289 10.5352 7.875 10.3673 7.875 10.1602C7.875 9.95305 8.04289 9.78516 8.25 9.78516C8.45711 9.78516 8.625 9.95305 8.625 10.1602ZM8.625 10.1602H8.25M12.375 10.1602C12.375 10.3673 12.2071 10.5352 12 10.5352C11.7929 10.5352 11.625 10.3673 11.625 10.1602C11.625 9.95305 11.7929 9.78516 12 9.78516C12.2071 9.78516 12.375 9.95305 12.375 10.1602ZM12.375 10.1602H12M16.125 10.1602C16.125 10.3673 15.9571 10.5352 15.75 10.5352C15.5429 10.5352 15.375 10.3673 15.375 10.1602C15.375 9.95305 15.5429 9.78516 15.75 9.78516C15.9571 9.78516 16.125 9.95305 16.125 10.1602ZM16.125 10.1602H15.75M2.25 13.1695C2.25 14.7706 3.37341 16.1642 4.95746 16.3971C6.04357 16.5568 7.14151 16.6801 8.25 16.7658V21.4102L12.4335 17.2267C12.6402 17.0199 12.9193 16.9024 13.2116 16.8952C15.1872 16.8462 17.1331 16.6779 19.0425 16.3972C20.6266 16.1643 21.75 14.7707 21.75 13.1696V7.15071C21.75 5.54962 20.6266 4.15598 19.0425 3.92309C16.744 3.58517 14.3926 3.41016 12.0003 3.41016C9.60776 3.41016 7.25612 3.5852 4.95747 3.92318C3.37342 4.15609 2.25 5.54972 2.25 7.1508V13.1695Z" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                                    </svg>
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Sidebar Social Links -->
                    <div class="!wpuf-mt-6">
                        <?php if ( $social_media['has_social'] ) : ?>
                        <h3 class="!wpuf-text-xs !wpuf-font-bold !wpuf-text-gray-500 !wpuf-mb-4 !wpuf-uppercase !wpuf-tracking-wider">
                            <?php esc_html_e( 'SOCIAL', 'wpuf-pro' ); ?>
                        </h3>
                        <div class="!wpuf-bg-white !wpuf-rounded-lg !wpuf-border !wpuf-border-gray-200 !wpuf-divide-y !wpuf-divide-gray-200">
                            <?php foreach ( $social_media['user_social'] as $field => $social_item ) : ?>
                                <a href="<?php echo esc_url( $social_item['url'] ); ?>" target="_blank" class="!wpuf-flex !wpuf-items-center !wpuf-justify-between !wpuf-px-4 !wpuf-py-2 !wpuf-text-sm !wpuf-text-gray-700 hover:!wpuf-bg-gray-50 !wpuf-no-underline !wpuf-transition-colors !wpuf-group">
                                    <div class="!wpuf-flex !wpuf-items-center !wpuf-gap-3">
                                        <span class="!wpuf-w-5 !wpuf-h-5 !wpuf-rounded-full !wpuf-bg-gray-900 !wpuf-text-white !wpuf-flex !wpuf-items-center !wpuf-justify-center">
                                            <?php echo str_replace( 'class="!wpuf-w-5 !wpuf-h-5"', 'class="!wpuf-w-3 !wpuf-h-3"', $social_item['icon_html'] ); ?>
                                        </span>
                                        <span class="!wpuf-font-normal"><?php echo esc_html( $social_item['label'] ); ?></span>
                                    </div>
                                    <svg width="15" height="17" viewBox="0 0 15 17" fill="none" xmlns="http://www.w3.org/2000/svg" class="!wpuf-opacity-60 group-hover:!wpuf-opacity-100 !wpuf-transition-opacity">
                                        <path d="M6.64384 4.14385C7.13608 3.65157 7.80379 3.375 8.50003 3.375H14C14.3452 3.375 14.625 3.65483 14.625 4C14.625 4.34518 14.3452 4.625 14 4.625H8.50003C8.13535 4.625 7.78561 4.76987 7.52776 5.02773C7.26982 5.28559 7.12501 5.63533 7.12501 6V8.50001C7.12501 8.84518 6.84517 9.12501 6.5 9.12501C6.15482 9.12501 5.875 8.84518 5.875 8.50001V6C5.875 5.30381 6.15156 4.63613 6.64384 4.14385Z" fill="#9CA3AF"/>
                                        <path d="M10.5581 0.558059C10.8021 0.31398 11.1979 0.31398 11.442 0.558059L14.4419 3.55806C14.686 3.80214 14.686 4.19787 14.4419 4.44195L11.442 7.44194C11.1979 7.68602 10.8021 7.68602 10.5581 7.44194C10.314 7.19786 10.314 6.80213 10.5581 6.55806L13.1161 4L10.5581 1.44194C10.314 1.19787 10.314 0.802136 10.5581 0.558059Z" fill="#9CA3AF"/>
                                        <path d="M1.99999 6.625C1.90054 6.625 1.80515 6.6645 1.73483 6.73483C1.6645 6.80516 1.62499 6.90055 1.62499 6.99999V15C1.62499 15.0995 1.6645 15.1949 1.73483 15.2652C1.80515 15.3355 1.90054 15.375 1.99999 15.375H11C11.0994 15.375 11.1948 15.3355 11.2652 15.2652C11.3355 15.1949 11.375 15.0995 11.375 15V9.99998C11.375 9.65483 11.6548 9.37502 12 9.37502C12.3452 9.37502 12.625 9.65483 12.625 9.99998V15C12.625 15.4309 12.4538 15.8443 12.1491 16.1491C11.8443 16.4538 11.431 16.625 11 16.625H1.99999C1.56902 16.625 1.1557 16.4538 0.850947 16.1491C0.546198 15.8443 0.375 15.4309 0.375 15V6.99999C0.375 6.56902 0.546198 6.1557 0.850947 5.85095C1.1557 5.5462 1.56902 5.375 1.99999 5.375H3.5C3.84518 5.375 4.12499 5.65482 4.12499 6C4.12499 6.34517 3.84518 6.625 3.5 6.625H1.99999Z" fill="#9CA3AF"/>
                                    </svg>
                                </a>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>

                        <!-- Bio Section -->
                        <?php if ( $user_meta['bio'] ) : ?>
                        <div class="!wpuf-mt-6">
                            <h3 class="!wpuf-text-xs !wpuf-font-bold !wpuf-text-gray-600 !wpuf-mb-3 !wpuf-uppercase !wpuf-tracking-wide">
                                <?php esc_html_e( 'Bio', 'wpuf-pro' ); ?>
                            </h3>
                            <?php
                            $full_bio = $user_meta['bio'];
                            $word_count = str_word_count( $full_bio );
                            $needs_toggle = $word_count > 150;
                            $bio_id = 'bio-layout1-' . $user->ID . '-' . uniqid();
                            ?>

                            <?php if ( $needs_toggle ) : ?>
                                <p class="!wpuf-text-sm !wpuf-font-normal !wpuf-text-black-600 !wpuf-leading-relaxed">
                                    <span id="<?php echo esc_attr( $bio_id . '-excerpt' ); ?>">
                                        <?php echo esc_html( wp_trim_words( $full_bio, 150, '' ) ); ?>...
                                    </span>
                                    <span id="<?php echo esc_attr( $bio_id . '-full' ); ?>" style="display: none;">
                                        <?php echo esc_html( $full_bio ); ?>
                                    </span>
                                    <button type="button"
                                            onclick="wpuf_toggleBio_layout1('<?php echo esc_js( $bio_id ); ?>')"
                                            id="<?php echo esc_attr( $bio_id . '-btn' ); ?>"
                                            class="!wpuf-text-sm !wpuf-font-medium !wpuf-text-gray-700 hover:!wpuf-text-gray-900 !wpuf-bg-transparent !wpuf-border-0 !wpuf-p-0 !wpuf-cursor-pointer !wpuf-ml-1">
                                        <?php esc_html_e( 'Show More', 'wpuf-pro' ); ?>
                                    </button>
                                    <button type="button"
                                            onclick="wpuf_toggleBio_layout1('<?php echo esc_js( $bio_id ); ?>')"
                                            id="<?php echo esc_attr( $bio_id . '-btn-less' ); ?>"
                                            style="display: none;"
                                            class="!wpuf-text-sm !wpuf-font-medium !wpuf-text-gray-700 hover:!wpuf-text-gray-900 !wpuf-bg-transparent !wpuf-border-0 !wpuf-p-0 !wpuf-cursor-pointer !wpuf-ml-1">
                                        <?php esc_html_e( 'Show Less', 'wpuf-pro' ); ?>
                                    </button>
                                </p>
                            <?php else : ?>
                                <p class="!wpuf-text-sm !wpuf-font-normal !wpuf-text-black-600 !wpuf-leading-relaxed">
                                    <?php echo esc_html( $full_bio ); ?>
                                </p>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Main Content Area -->
            <div class="lg:!wpuf-col-span-8 xl:!wpuf-col-span-9">
                <!-- Tab Navigation -->
                <?php if ( $enable_tabs && ! empty( $default_tabs ) ) : ?>
                <div class="!wpuf-bg-transparent !wpuf-rounded-lg !wpuf-overflow-hidden">
                    <div class="!wpuf-border-b !wpuf-border-gray-200">
                        <nav class="!wpuf-flex !wpuf-space-x-12 !wpuf-px-6" aria-label="Tabs">
                            <?php foreach ( $default_tabs as $tab ) : ?>
                                <?php
                                // Skip activity tab if User Activity module is not active
                                if ( $tab === 'activity' && ! class_exists( 'WPUF_User_Activity' ) ) {
                                    continue;
                                }

                                if ( in_array( $tab, [ 'about', 'posts', 'comments', 'file', 'activity' ] ) ) :
                                ?>
                                    <button class="wpuf-tab-button <?php echo $tab === $default_active_tab ? 'active' : ''; ?> !wpuf-relative !wpuf-py-4 !wpuf-px-8 !wpuf-font-medium !wpuf-text-sm !wpuf-transition-all !wpuf-duration-200 !wpuf-text-gray-500 hover:!wpuf-text-gray-700 hover:!wpuf-bg-transparent !wpuf-bg-transparent active:!wpuf-bg-transparent"
                                            data-tab="<?php echo esc_attr( $tab ); ?>">
                                        <?php echo esc_html( wpuf_ud_get_tab_label( $tab, $profile_data ) ); ?>
                                    </button>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </nav>
                    </div>

                    <!-- Tab Content -->
                    <div class="wpuf-p-6">
                        <!-- About Tab -->
                        <div class="wpuf-tab-content-about" style="<?php echo $default_active_tab !== 'about' ? 'display: none;' : ''; ?>">
                            <?php
                            // Include about-1 template part with new design
                            if ( file_exists( WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/about-1.php' ) ) {
                                include WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/about-1.php';
                            } elseif ( file_exists( WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/user-bio.php' ) ) {
                                // Fallback to old template parts
                                $user_bio = get_user_meta( $user->ID, 'description', true );
                                include WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/user-bio.php';
                                $tab_title = __( 'About', 'wpuf-pro' );
                                if ( file_exists( WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/about.php' ) ) {
                                    include WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/about.php';
                                }
                            }
                            ?>
                        </div>

                        <!-- Posts Tab -->
                        <?php if ( in_array( 'posts', $default_tabs ) ) : ?>
                            <div class="wpuf-tab-content-posts" style="<?php echo $default_active_tab !== 'posts' ? 'display: none;' : ''; ?>">
                                <?php
                                if ( file_exists( WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/posts-1.php' ) ) {
                                    include WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/posts-1.php';
                                } elseif ( file_exists( WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/posts.php' ) ) {
                                    // Fallback to old template
                                    include WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/posts.php';
                                }
                                ?>
                            </div>
                        <?php endif; ?>

                        <!-- Comments Tab -->
                        <?php if ( in_array( 'comments', $default_tabs ) ) : ?>
                            <div class="wpuf-tab-content-comments" style="<?php echo $default_active_tab !== 'comments' ? 'display: none;' : ''; ?>">
                                <?php
                                $tab_title = __( 'Comments', 'wpuf-pro' );
                                if ( file_exists( WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/comments-1.php' ) ) {
                                    include WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/comments-1.php';
                                } elseif ( file_exists( WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/comments.php' ) ) {
                                    // Fallback to old template
                                    include WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/comments.php';
                                }
                                ?>
                            </div>
                        <?php endif; ?>

                        <!-- File Tab -->
                        <?php if ( in_array( 'file', $default_tabs ) ) : ?>
                            <div class="wpuf-tab-content-file" style="<?php echo $default_active_tab !== 'file' ? 'display: none;' : ''; ?>">
                                <?php
                                $tab_title = __( 'Files', 'wpuf-pro' );
                                if ( file_exists( WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/file-1.php' ) ) {
                                    include WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/file-1.php';
                                } elseif ( file_exists( WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/file.php' ) ) {
                                    // Fallback to old template
                                    include WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/file.php';
                                }
                                ?>
                            </div>
                        <?php endif; ?>

                        <!-- Activity Tab -->
                        <?php if ( in_array( 'activity', $default_tabs ) && class_exists( 'WPUF_User_Activity' ) ) : ?>
                            <div class="wpuf-tab-content-activity" style="<?php echo $default_active_tab !== 'activity' ? 'display: none;' : ''; ?>">
                                <?php
                                if ( file_exists( WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/activity-1.php' ) ) {
                                    include WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/activity-1.php';
                                } elseif ( file_exists( WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/activity.php' ) ) {
                                    // Fallback to old template
                                    include WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/activity.php';
                                }
                                ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php else : ?>
                    <!-- No tabs - show about content directly -->
                    <div class="!wpuf-bg-white !wpuf-rounded-lg !wpuf-shadow-sm !wpuf-p-6">
                        <?php
                        if ( file_exists( WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/about-1.php' ) ) {
                            include WPUF_UD_TEMPLATES . '/shortcodes/profile/template-parts/about-1.php';
                        }
                        ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
</div>

<!-- Tab Switching JavaScript -->
<script type="text/javascript">
jQuery(document).ready(function($) {
    // Function to get URL parameter
    function getUrlParameter(name) {
        name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
        var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
        var results = regex.exec(location.search);
        return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
    }

    // Function to build clean URL for tab switching
    function buildCleanTabUrl(targetTab) {
        var currentUrl = new URL(window.location.href);

        // Define ALL tab pagination parameters that should be cleaned
        var allTabPaginationParams = ['posts_page', 'comments_page', 'cpage'];

        // Define pagination parameters for each tab
        var tabPaginationParams = {
            'posts': ['posts_page'],
            'comments': ['comments_page'],
            'activity': ['cpage'],
            'about': [],
            'file': [],
            'message': []
        };

        // Get directory-related parameters to preserve (these persist across all tabs)
        var directoryParams = ['dir_page', 'orderby', 'order', 'search'];

        // Start with a clean URL (path only)
        var cleanUrl = new URL(currentUrl.origin + currentUrl.pathname);

        // Always add the target tab
        cleanUrl.searchParams.set('tab', targetTab);

        // Preserve directory-related parameters across all tabs
        directoryParams.forEach(function(param) {
            var value = currentUrl.searchParams.get(param);
            if (value) {
                cleanUrl.searchParams.set(param, value);
            }
        });

        // ONLY preserve pagination params relevant to the target tab
        // This explicitly excludes other tabs' pagination parameters
        if (tabPaginationParams[targetTab] && tabPaginationParams[targetTab].length > 0) {
            tabPaginationParams[targetTab].forEach(function(param) {
                var value = currentUrl.searchParams.get(param);
                if (value) {
                    cleanUrl.searchParams.set(param, value);
                }
            });
        }
        // Note: We don't add any other pagination parameters, so they're automatically excluded

        return cleanUrl.toString();
    }

    // IMPORTANT: Always prioritize tab parameter from URL over any other detection
    var urlTab = getUrlParameter('tab');

    // If no explicit tab parameter, check for pagination parameters that indicate a specific tab
    if (!urlTab) {
        if (getUrlParameter('cpage')) {
            urlTab = 'activity'; // cpage is used by activity pagination
        } else if (getUrlParameter('posts_page')) {
            urlTab = 'posts';
        } else if (getUrlParameter('comments_page')) {
            urlTab = 'comments';
        }
    }

    if (urlTab) {
        // Activate the tab from URL
        var $targetTabButton = $('.wpuf-tab-button[data-tab="' + urlTab + '"]');
        if ($targetTabButton.length) {
            // Remove active class from all tabs
            $('.wpuf-tab-button').removeClass('active !wpuf-text-gray-900').addClass('!wpuf-text-gray-500');

            // Add active class to target tab
            $targetTabButton.addClass('active !wpuf-text-gray-900').removeClass('!wpuf-text-gray-500');

            // Hide all tab content divs
            $('[class^="wpuf-tab-content-"]').hide();

            // Show target tab content
            $('.wpuf-tab-content-' + urlTab).show();
        }
    }

    // Tab switching functionality
    $('.wpuf-tab-button').on('click', function(e) {
        e.preventDefault();

        var targetTab = $(this).data('tab');
        var $tabsContainer = $(this).closest('.wpuf-profile-layout-1');

        // Remove active class from all tab buttons
        $tabsContainer.find('.wpuf-tab-button').removeClass('active !wpuf-text-gray-900').addClass('!wpuf-text-gray-500');

        // Add active class to clicked tab button
        $(this).addClass('active !wpuf-text-gray-900').removeClass('!wpuf-text-gray-500');

        // Hide all tab content divs
        $tabsContainer.find('[class^="wpuf-tab-content-"]').hide();

        // Show target tab content
        $tabsContainer.find('.wpuf-tab-content-' + targetTab).show();

        // Update URL without reloading page - clean other tab pagination parameters
        if (history.pushState) {
            var cleanUrl = buildCleanTabUrl(targetTab);
            history.pushState({tab: targetTab}, '', cleanUrl);
        }
    });

    // Set initial active tab styling
    $('.wpuf-tab-button.active').removeClass('!wpuf-text-gray-500').addClass('!wpuf-text-gray-900');
});

// Back button functionality
function wpuf_ud_goBack() {
    // 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();
}

// Bio toggle for layout-1
function wpuf_toggleBio_layout1(bioId) {
    var excerpt = document.getElementById(bioId + '-excerpt');
    var full = document.getElementById(bioId + '-full');
    var showBtn = document.getElementById(bioId + '-btn');
    var hideBtn = document.getElementById(bioId + '-btn-less');

    if (full.style.display === 'none') {
        excerpt.style.display = 'none';
        full.style.display = 'inline';
        showBtn.style.display = 'none';
        hideBtn.style.display = 'inline';
    } else {
        excerpt.style.display = 'inline';
        full.style.display = 'none';
        showBtn.style.display = 'inline';
        hideBtn.style.display = 'none';
    }
}
</script>

<!-- Additional Tailwind Styles -->
<style>
.wpuf-tab-button {
    position: relative;
}
.wpuf-tab-button::after {
    content: '';
    position: absolute;
    bottom: -1px;
    left: -20px;
    right: -20px;
    height: 3px;
    background-color: transparent;
    transition: background-color 0.2s;
}
.wpuf-tab-button.active::after {
    background-color: #1f2937; /* Gray/800 */
}
.wpuf-tab-button.active {
    @apply !wpuf-text-gray-900 !wpuf-font-semibold;
}
.wpuf-tab-button:focus {
    outline: none;
}
</style>
