/**
 * User Directory Profile Layout - Unified Tab/Navigation Script
 *
 * Replaces profile-layout-1.js through profile-layout-4.js with a single
 * parameterized script. Configuration is passed via wp_localize_script().
 *
 * @package WPUF_Pro
 * @subpackage Modules/User_Directory
 * @since 4.2.14
 */

'use strict';

jQuery( document ).ready( function( $ ) {
    // Get configuration from wp_localize_script (set in ShortCode.php)
    var config = ( typeof wpuf_ud_profile_config !== 'undefined' ) ? wpuf_ud_profile_config : {};

    var tabButtonClass    = config.tabButtonClass || '.wpuf-tab-button';
    var containerClass    = config.containerClass || '.wpuf-profile-layout-1';
    var tabContentClass   = config.tabContentClass || '';
    var activeClass       = config.activeClass || 'active !wpuf-text-gray-900';
    var inactiveClass     = config.inactiveClass || '!wpuf-text-gray-500';
    var tabContentSelector = config.tabContentSelector || '[class^="wpuf-tab-content-"]';

    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 buildCleanTabUrl( targetTab ) {
        var currentUrl = new URL( window.location.href );

        var tabPaginationParams = {
            'posts'    : [ 'posts_page' ],
            'comments' : [ 'comments_page' ],
            'activity' : [ 'cpage' ],
            'about'    : [],
            'file'     : [],
            'message'  : []
        };

        var directoryParams = [ 'dir_page', 'orderby', 'order', 'search' ];
        var cleanUrl        = new URL( currentUrl.origin + currentUrl.pathname );

        cleanUrl.searchParams.set( 'tab', targetTab );

        directoryParams.forEach( function( param ) {
            var value = currentUrl.searchParams.get( param );
            if ( value ) {
                cleanUrl.searchParams.set( param, value );
            }
        } );

        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 );
                }
            } );
        }

        return cleanUrl.toString();
    }

    // Detect active tab from URL
    var urlTab = getUrlParameter( 'tab' );

    if ( ! urlTab ) {
        if ( getUrlParameter( 'cpage' ) ) {
            urlTab = 'activity';
        } else if ( getUrlParameter( 'posts_page' ) ) {
            urlTab = 'posts';
        } else if ( getUrlParameter( 'comments_page' ) ) {
            urlTab = 'comments';
        }
    }

    if ( urlTab ) {
        var $targetTabButton = $( tabButtonClass + '[data-tab="' + urlTab + '"]' );
        if ( $targetTabButton.length ) {
            $( tabButtonClass ).removeClass( 'active ' + activeClass ).addClass( inactiveClass );
            $targetTabButton.addClass( 'active ' + activeClass ).removeClass( inactiveClass );

            if ( tabContentClass ) {
                $( tabContentClass + ' > div' ).hide();
            } else {
                $( tabContentSelector ).hide();
            }
            $( '.wpuf-tab-content-' + urlTab ).show();
        }
    }

    // Tab switching
    $( tabButtonClass ).on( 'click', function( e ) {
        e.preventDefault();

        var targetTab      = $( this ).data( 'tab' );
        var $tabsContainer = $( this ).closest( containerClass );

        $tabsContainer.find( tabButtonClass ).removeClass( 'active ' + activeClass ).addClass( inactiveClass );
        $( this ).addClass( 'active ' + activeClass ).removeClass( inactiveClass );

        if ( tabContentClass ) {
            $tabsContainer.find( tabContentClass + ' > div' ).hide();
        } else {
            $tabsContainer.find( tabContentSelector ).hide();
        }
        $tabsContainer.find( '.wpuf-tab-content-' + targetTab ).show();

        if ( history.pushState ) {
            var cleanUrl = buildCleanTabUrl( targetTab );
            history.pushState( { tab: targetTab }, '', cleanUrl );
        }
    } );

    // Set initial active tab styling
    $( tabButtonClass + '.active' ).removeClass( inactiveClass ).addClass( activeClass );
} );

// Back button — shared across all layouts, defined once
if ( typeof wpuf_ud_goBack === 'undefined' ) {
window.wpuf_ud_goBack = function() { // eslint-disable-line no-unused-vars
    var currentUrl = new URL( window.location.href );
    var dirPage    = currentUrl.searchParams.get( 'dir_page' );

    if ( ! dirPage && document.referrer && document.referrer.includes( window.location.hostname ) ) {
        var referrerUrl  = new URL( document.referrer );
        var referrerPath = referrerUrl.pathname.replace( /\/+$/, '' );
        var currentPath  = currentUrl.pathname.replace( /\/[^\/]+\/?$/, '' ).replace( /\/+$/, '' );

        if (
            referrerPath === currentPath ||
            referrerPath.includes( '/page/' ) ||
            referrerUrl.searchParams.has( 'page' ) ||
            referrerUrl.searchParams.has( 'orderby' ) ||
            referrerUrl.searchParams.has( 'order' ) ||
            referrerUrl.searchParams.has( 'search' )
        ) {
            referrerUrl.searchParams.delete( 'tab' );
            referrerUrl.searchParams.delete( 'cpage' );
            window.location.href = referrerUrl.toString();
            return;
        }
    }

    var url = new URL( window.location.href );
    dirPage = url.searchParams.get( 'dir_page' );

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

    url.search = '';

    var pathParts = url.pathname.split( '/' ).filter( function( part ) {
        return part !== '';
    } );

    if ( pathParts.length > 0 ) {
        pathParts.pop();
    }

    url.pathname = '/' + pathParts.join( '/' ) + '/';

    if ( dirPage && dirPage > 1 ) {
        url.pathname = url.pathname.replace( /\/$/, '' ) + '/page/' + dirPage + '/';
    }

    Object.keys( preserveParams ).forEach( function( param ) {
        url.searchParams.set( param, preserveParams[ param ] );
    } );

    window.location.href = url.toString();
};
} // End wpuf_ud_goBack guard

// Bio toggle — unified, replaces wpuf_toggleBio_layout{N} variants
function wpuf_toggleBio( bioId ) { // eslint-disable-line no-unused-vars
    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';
    }
}

// Backward-compatible aliases so existing templates continue to work
window.wpuf_toggleBio_layout1 = wpuf_toggleBio;
window.wpuf_toggleBio_layout2 = wpuf_toggleBio;
window.wpuf_toggleBio_layout4 = wpuf_toggleBio;
