<?php
/**
 * Main User Profile Template Router
 *
 * This template determines which profile layout to load based on the profile_layout parameter.
 * It serves as the main entry point for profile rendering in shortcode context.
 *
 * @since 4.2.0
 *
 * Available variables:
 * @var array $template_data Complete profile data
 * @var string $profile_layout Selected profile layout (layout-1, layout-2, etc.)
 */

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

// Extract template data
$user = $template_data['user'];
$profile_layout = ! empty( $profile_layout ) ? $profile_layout : 'layout-1';

// Validate user
if ( ! $user || is_wp_error( $user ) ) {
    ?>
    <div class="wpuf-user-profile-error !wpuf-flex !wpuf-items-center !wpuf-justify-center !wpuf-min-h-[300px] !wpuf-bg-gray-50 !wpuf-rounded-lg">
        <div class="!wpuf-text-center">
            <div class="!wpuf-text-6xl !wpuf-text-gray-300 !wpuf-mb-4">👤</div>
            <h1 class="!wpuf-text-2xl !wpuf-font-bold !wpuf-text-gray-700 !wpuf-mb-2">
                <?php esc_html_e( 'User Not Found', 'wpuf-pro' ); ?>
            </h1>
            <p class="!wpuf-text-gray-500">
                <?php esc_html_e( 'The requested user profile could not be found.', 'wpuf-pro' ); ?>
            </p>
            <button onclick="wpuf_ud_goBack()"
                    class="!wpuf-inline-block !wpuf-mt-4 !wpuf-px-4 !wpuf-py-2 !wpuf-bg-primary !wpuf-text-white !wpuf-rounded !wpuf-text-sm !wpuf-no-underline hover:!wpuf-bg-primary-dark !wpuf-border-none !wpuf-cursor-pointer">
                <?php esc_html_e( '← Back to Directory', 'wpuf-pro' ); ?>
            </button>
            <script>
            // Back button functionality for user-profile.php
            function wpuf_ud_goBack() {
                // Try to use browser history first to preserve pagination and other parameters
                if (document.referrer && document.referrer.includes(window.location.hostname)) {
                    var referrerUrl = new URL(document.referrer);
                    var currentUrl = new URL(window.location.href);

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

                    // If coming from directory page, use referrer but remove tab parameter
                    if (referrerPath === currentPath ||
                        referrerUrl.searchParams.has('page') ||
                        referrerUrl.searchParams.has('orderby') ||
                        referrerUrl.searchParams.has('order') ||
                        referrerUrl.searchParams.has('search')) {

                        // Remove tab parameter from referrer URL
                        referrerUrl.searchParams.delete('tab');
                        window.location.href = referrerUrl.toString();
                        return;
                    }
                }

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

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

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

                // Handle clean URLs by removing the last path segment if it exists
                var pathParts = url.pathname.split('/').filter(part => part !== '');
                if (pathParts.length > 1) {
                    // Remove the last segment (user identifier) and rebuild the path
                    pathParts.pop();
                    url.pathname = '/' + pathParts.join('/') + '/';
                }

                // 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();
            }
            </script>
        </div>
    </div>
    <?php
    return;
}

// Generate unique container ID
$container_id = 'wpuf-profile-' . $user->ID . '-' . uniqid();

// Add container wrapper with Tailwind classes
echo '<div id="' . esc_attr( $container_id ) . '" class="wpuf-user-profile-container" data-layout="' . esc_attr( $profile_layout ) . '">';

// Determine which layout template to load
$layout_template = 'layout-1'; // Default fallback

// Validate and set layout template
$available_layouts = [ 'layout-1', 'layout-2', 'layout-3' ];
if ( in_array( $profile_layout, $available_layouts, true ) ) {
    $layout_template = $profile_layout;
}

// Load the specific layout template
$layout_file = WPUF_UD_TEMPLATES . '/shortcodes/profile/' . $layout_template . '.php';

if ( file_exists( $layout_file ) ) {
    include $layout_file;
} else {
    // Fallback to layout-1 if specified layout doesn't exist
    include WPUF_UD_TEMPLATES . '/shortcodes/profile/layout-1.php';
}

echo '</div>';

// Add inline CSS for Tailwind compatibility if needed
?>
<style>
/* Profile-specific Tailwind utilities */
.wpuf-user-profile-container {
    @apply wpuf-max-w-full wpuf-mx-auto;
}

/* Ensure proper spacing and responsive behavior */
.wpuf-user-profile-container .wpuf-back-btn {
    @apply wpuf-inline-flex wpuf-items-center wpuf-px-3 wpuf-py-2 wpuf-text-sm wpuf-font-medium wpuf-text-gray-700 wpuf-bg-white wpuf-border wpuf-border-gray-300 wpuf-rounded-md wpuf-shadow-sm hover:wpuf-bg-gray-50 wpuf-transition-colors wpuf-duration-200 wpuf-no-underline;
}

.wpuf-user-profile-container .wpuf-avatar-container img {
    @apply wpuf-rounded-full wpuf-border-4 wpuf-border-white wpuf-shadow-lg;
}

.wpuf-user-profile-container .wpuf-profile-tabs {
    @apply wpuf-border-b wpuf-border-gray-200;
}

.wpuf-user-profile-container .wpuf-tab-button {
    @apply wpuf-px-4 wpuf-py-2 wpuf-text-sm wpuf-font-medium wpuf-text-gray-500 wpuf-border-b-2 wpuf-border-transparent hover:wpuf-text-gray-700 hover:wpuf-border-gray-300 wpuf-transition-colors wpuf-duration-200 wpuf-no-underline;
}

.wpuf-user-profile-container .wpuf-tab-button.active {
    @apply wpuf-text-primary wpuf-border-primary;
}

.wpuf-user-profile-container .wpuf-tab-content {
    @apply wpuf-mt-6;
}

/* Responsive design */
@media (max-width: 768px) {
    .wpuf-user-profile-container {
        @apply wpuf-px-4;
    }
}
</style>
