<?php
/**
 * User Tabs Ajax Handler
 *
 * Handles AJAX requests for user tabs functionality
 *
 * @since 4.2.0
 * @package WPUF\UserDirectory
 */

namespace WPUF\UserDirectory;

use WPUF\UserDirectory\FileHelper;

/**
 * User Tabs AJAX Handler
 * Handles dynamic loading of tab content via AJAX
 *
 * @since 4.2.0
 * @package WPUF_Pro
 */
class UserTabsAjaxHandler {

    /**
     * Constructor
     *
     * @since 4.2.0
     */
    public function __construct() {
        add_action( 'wp_ajax_wpuf_load_user_posts', [ $this, 'load_user_posts' ] );
        add_action( 'wp_ajax_nopriv_wpuf_load_user_posts', [ $this, 'load_user_posts' ] );

        add_action( 'wp_ajax_wpuf_load_user_comments', [ $this, 'load_user_comments' ] );
        add_action( 'wp_ajax_nopriv_wpuf_load_user_comments', [ $this, 'load_user_comments' ] );

        add_action( 'wp_ajax_wpuf_load_user_files', [ $this, 'load_user_files' ] );
        add_action( 'wp_ajax_nopriv_wpuf_load_user_files', [ $this, 'load_user_files' ] );

        add_action( 'wp_ajax_wpuf_load_user_activity', [ $this, 'load_user_activity' ] );
        add_action( 'wp_ajax_nopriv_wpuf_load_user_activity', [ $this, 'load_user_activity' ] );

        add_action( 'wp_ajax_wpuf_load_user_posts_block', [ $this, 'load_user_posts_block' ] );
        add_action( 'wp_ajax_nopriv_wpuf_load_user_posts_block', [ $this, 'load_user_posts_block' ] );

        add_action( 'wp_ajax_wpuf_load_user_comments_block', [ $this, 'load_user_comments_block' ] );
        add_action( 'wp_ajax_nopriv_wpuf_load_user_comments_block', [ $this, 'load_user_comments_block' ] );
    }

    /**
     * Load user posts for the Posts tab
     *
     * @since 4.2.0
     */
    public function load_user_posts() {
        // Verify nonce
        if ( ! wp_verify_nonce( $_POST['nonce'], 'wpuf_user_tabs_nonce' ) ) {
            wp_die( __( 'Security check failed', 'wpuf-pro' ) );
        }

        $user_id = absint( $_POST['user_id'] );
        $posts_per_page = absint( $_POST['posts_per_page'] ) ?: 5;
        $show_excerpts = $_POST['show_excerpts'] === 'true';
        $current_page = absint( $_POST['current_page'] ) ?: 1;
        $show_pagination = $_POST['show_pagination'] === 'true';

        if ( ! $user_id ) {
            wp_send_json_error( [ 'message' => __( 'Invalid user ID', 'wpuf-pro' ) ] );
        }

        $user = get_user_by( 'ID', $user_id );
        if ( ! $user ) {
            wp_send_json_error( [ 'message' => __( 'User not found', 'wpuf-pro' ) ] );
        }

        // Calculate offset for pagination
        $offset = ( $current_page - 1 ) * $posts_per_page;

        $posts = get_posts( [
            'author'      => $user_id,
            'numberposts' => $posts_per_page,
            'offset'      => $offset,
            'post_status' => 'publish',
            'orderby'     => 'date',
            'order'       => 'DESC',
        ] );

        // Get total posts count for pagination using WP_Query for better performance
        $count_query = new \WP_Query( [
            'author'      => $user_id,
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'fields'      => 'ids',
            'no_found_rows' => false, // We need the total count
        ] );
        $total_posts_count = $count_query->found_posts;

        if ( empty( $posts ) ) {
            wp_send_json_error( [ 'message' => __( 'No posts found', 'wpuf-pro' ) ] );
        }

        $html = '<div class="wpuf-overflow-hidden wpuf-shadow wpuf-outline wpuf-outline-1 wpuf-outline-black/5 wpuf-rounded-lg wpuf-dark:shadow-none wpuf-dark:-outline-offset-1 wpuf-dark:outline-white/10">';
        $html .= '<table class="wpuf-relative wpuf-min-w-full wpuf-divide-y wpuf-divide-gray-300 wpuf-dark:divide-white/15">';

        // Table header
        $html .= '<thead class="wpuf-bg-gray-50 wpuf-dark:bg-gray-800/75">';
        $html .= '<tr>';
        $html .= '<th scope="col" class="wpuf-py-3.5 wpuf-pr-3 wpuf-pl-4 wpuf-text-left wpuf-text-sm wpuf-font-semibold wpuf-text-gray-900 wpuf-sm:pl-6 wpuf-dark:text-gray-200">';
        $html .= esc_html__( 'Post Title', 'wpuf-pro' );
        $html .= '</th>';
        $html .= '<th scope="col" class="wpuf-px-3 wpuf-py-3.5 wpuf-text-left wpuf-text-sm wpuf-font-semibold wpuf-text-gray-900 wpuf-dark:text-gray-200">';
        $html .= esc_html__( 'Publish Date', 'wpuf-pro' );
        $html .= '</th>';
        $html .= '<th scope="col" class="wpuf-py-3.5 wpuf-pr-4 wpuf-pl-3 wpuf-sm:pr-6">';
        $html .= '<span class="wpuf-sr-only">' . esc_html__( 'View', 'wpuf-pro' ) . '</span>';
        $html .= '</th>';
        $html .= '</tr>';
        $html .= '</thead>';

        // Table body
        $html .= '<tbody class="wpuf-divide-y wpuf-divide-gray-200 wpuf-bg-white wpuf-dark:divide-white/10 wpuf-dark:bg-gray-800/50">';

        foreach ( $posts as $post ) {
            $html .= '<tr>';
            $html .= '<td class="wpuf-py-4 wpuf-pr-3 wpuf-pl-4 wpuf-text-sm wpuf-font-medium wpuf-whitespace-nowrap wpuf-text-gray-900 wpuf-sm:pl-6 wpuf-dark:text-white">';
            $html .= esc_html( get_the_title( $post->ID ) );
            $html .= '</td>';
            $html .= '<td class="wpuf-px-3 wpuf-py-4 wpuf-text-sm wpuf-whitespace-nowrap wpuf-text-gray-500 wpuf-dark:text-gray-400">';
            $html .= esc_html( get_the_date( 'F j, Y', $post->ID ) );
            $html .= '</td>';
            $html .= '<td class="wpuf-py-4 wpuf-pr-4 wpuf-pl-3 wpuf-text-right wpuf-text-sm wpuf-font-medium wpuf-whitespace-nowrap wpuf-sm:pr-6">';
            $html .= '<a href="' . esc_url( get_permalink( $post->ID ) ) . '" class="wpuf-text-indigo-600 wpuf-hover:text-indigo-900 wpuf-dark:text-indigo-400 wpuf-dark:hover:text-indigo-300">';
            $html .= esc_html__( 'Post Link ->', 'wpuf-pro' );
            $html .= '<span class="wpuf-sr-only">, ' . esc_html( get_the_title( $post->ID ) ) . '</span>';
            $html .= '</a>';
            $html .= '</td>';
            $html .= '</tr>';
        }

        $html .= '</tbody>';
        $html .= '</table>';
        $html .= '</div>';

        // Add pagination if enabled and there are multiple pages
        $pagination_html = '';
        $total_pages = 1;
        
        
        if ( $show_pagination && $total_posts_count > $posts_per_page ) {
            $total_pages = ceil( $total_posts_count / $posts_per_page );
            $pagination_html = $this->render_pagination_template( $current_page, $total_pages, $posts_per_page, $total_posts_count );
        }

        wp_send_json_success( [ 
            'html' => $html,
            'pagination' => $pagination_html,
            'pagination_data' => [
                'current_page' => $current_page,
                'total_pages' => $total_pages,
                'total_posts' => $total_posts_count,
                'posts_per_page' => $posts_per_page
            ]
        ] );
    }

    /**
     * Load user comments for the Comments tab
     *
     * @since 4.2.0
     */
    public function load_user_comments() {
        // Verify nonce
        if ( ! wp_verify_nonce( $_POST['nonce'], 'wpuf_user_tabs_nonce' ) ) {
            wp_die( __( 'Security check failed', 'wpuf-pro' ) );
        }

        $user_id = absint( $_POST['user_id'] );
        $comment_length = absint( $_POST['comment_length'] ) ?: 100;
        $comments_per_page = absint( $_POST['comments_per_page'] ) ?: 10;
        $current_page = absint( $_POST['current_page'] ) ?: 1;
        $show_pagination = $_POST['show_pagination'] === 'true';

        if ( ! $user_id ) {
            wp_send_json_error( [ 'message' => __( 'Invalid user ID', 'wpuf-pro' ) ] );
        }

        $user = get_user_by( 'ID', $user_id );
        if ( ! $user ) {
            wp_send_json_error( [ 'message' => __( 'User not found', 'wpuf-pro' ) ] );
        }

        // Calculate offset for pagination
        $offset = ( $current_page - 1 ) * $comments_per_page;

        $comments = get_comments( [
            'user_id' => $user_id,
            'number'  => $comments_per_page,
            'offset'  => $offset,
            'status'  => 'approve',
            'orderby' => 'comment_date',
            'order'   => 'DESC',
        ] );

        // Get total comments count for pagination
        $total_comments_count = get_comments( [
            'user_id' => $user_id,
            'status'  => 'approve',
            'count'   => true,
        ] );

        if ( empty( $comments ) ) {
            wp_send_json_error( [ 'message' => __( 'No comments found', 'wpuf-pro' ) ] );
        }

        // Modern minimal design wrapper
        $html = '<div class="wpuf-overflow-hidden wpuf-shadow wpuf-outline wpuf-outline-1 wpuf-outline-black/5 wpuf-rounded-lg wpuf-dark:shadow-none wpuf-dark:-outline-offset-1 wpuf-dark:outline-white/10">';
        $html .= '<div class="wpuf-divide-y wpuf-divide-gray-200 wpuf-bg-white wpuf-dark:divide-white/10 wpuf-dark:bg-gray-800/50">';

        foreach ( $comments as $comment ) {
            $comment_content = wp_strip_all_tags( $comment->comment_content );
            $comment_excerpt = wp_trim_words( $comment_content, 20, '...' );
            $comment_date    = date_i18n( 'M j, Y', strtotime( $comment->comment_date ) );
            $post_title     = get_the_title( $comment->comment_post_ID );
            $post_url       = get_permalink( $comment->comment_post_ID );
            $reply_count    = get_comments( [
                'parent' => $comment->comment_ID,
                'count'  => true,
            ] );

            $html .= sprintf(
                '<div class="wpuf-px-4 wpuf-py-4">
                    <div class="wpuf-flex wpuf-items-start wpuf-gap-3">
                        <div class="wpuf-flex-shrink-0">
                            <div class="wpuf-w-8 wpuf-h-8 wpuf-bg-gray-200 wpuf-dark:bg-gray-700 wpuf-rounded-full wpuf-flex wpuf-items-center wpuf-justify-center">
                                <span class="wpuf-text-xs wpuf-font-medium wpuf-text-gray-600 wpuf-dark:text-gray-300">%s</span>
                            </div>
                        </div>
                        <div class="wpuf-flex-1 wpuf-min-w-0">
                            <div class="wpuf-flex wpuf-items-center wpuf-gap-2 wpuf-mb-1">
                                <span class="wpuf-text-sm wpuf-font-medium wpuf-text-gray-900 wpuf-dark:text-white">%s</span>
                                <span class="wpuf-text-xs wpuf-text-gray-500 wpuf-dark:text-gray-400">%s</span>
                            </div>
                            <p class="wpuf-text-sm wpuf-text-gray-700 wpuf-dark:text-gray-300 wpuf-mb-2">%s</p>
                            <div class="wpuf-flex wpuf-items-center wpuf-gap-4 wpuf-text-xs wpuf-text-gray-500 wpuf-dark:text-gray-400">
                                <span>%s: <a href="%s" class="wpuf-text-indigo-600 wpuf-hover:text-indigo-900 wpuf-dark:text-indigo-400 wpuf-dark:hover:text-indigo-300">%s</a></span>%s
                            </div>
                        </div>
                    </div>
                </div>',
                esc_html( strtoupper( substr( $user->display_name, 0, 1 ) ) ),
                esc_html( $user->display_name ),
                esc_html( $comment_date ),
                esc_html( $comment_excerpt ),
                esc_html__( 'On', 'wpuf-pro' ),
                esc_url( $post_url ),
                esc_html( $post_title ),
                $reply_count > 0 ? sprintf( '<span>%d %s</span>', $reply_count, esc_html__( 'replies', 'wpuf-pro' ) ) : ''
            );
        }

        $html .= '</div>';
        $html .= '</div>';

        // Add pagination if enabled and there are multiple pages
        $pagination_html = '';
        $total_pages = 1;
        
        
        if ( $show_pagination && $total_comments_count > $comments_per_page ) {
            $total_pages = ceil( $total_comments_count / $comments_per_page );
            $pagination_html = $this->render_pagination_template( $current_page, $total_pages, $comments_per_page, $total_comments_count );
        }

        wp_send_json_success( [ 
            'html' => $html,
            'pagination' => $pagination_html,
            'pagination_data' => [
                'current_page' => $current_page,
                'total_pages' => $total_pages,
                'total_comments' => $total_comments_count,
                'comments_per_page' => $comments_per_page
            ]
        ] );
    }

    /**
     * Load user files for the Files tab
     *
     * @since 4.2.0
     */
    public function load_user_files() {
        // Verify nonce
        if ( ! wp_verify_nonce( $_POST['nonce'], 'wpuf_user_tabs_nonce' ) ) {
            wp_die( __( 'Security check failed', 'wpuf-pro' ) );
        }

        $user_id = absint( $_POST['user_id'] );

        if ( ! $user_id ) {
            wp_send_json_error( [ 'message' => __( 'Invalid user', 'wpuf-pro' ) ] );
        }

        $user = get_user_by( 'ID', $user_id );
        if ( ! $user ) {
            wp_send_json_error( [ 'message' => __( 'User not found', 'wpuf-pro' ) ] );
        }

        // Check if user has any files using the existing function
        if ( ! wpuf_ud_user_has_files( $user_id ) ) {
            wp_send_json_error( [ 'message' => __( 'No files found', 'wpuf-pro' ) ] );
        }

        // Prepare field configuration for the grouped files function
        $field_config = [
            'meta_key' => '', // Empty to get all user files
            'label' => __( 'Files', 'wpuf-pro' )
        ];

        // Start output buffering to capture the HTML output
        ob_start();

        // Use the new grouped files function
        wpuf_ud_render_files_grouped_by_type( $field_config, $user_id, [], 'gray' );

        // Get the captured HTML
        $html = ob_get_clean();

        if ( empty( $html ) ) {
            wp_send_json_error( [ 'message' => __( 'No files found', 'wpuf-pro' ) ] );
        }

        wp_send_json_success( [ 'html' => $html ] );
    }

    /**
     * Load user activity for the Activity tab
     *
     * @since 4.2.0
     */
    public function load_user_activity() {
        // Verify nonce
        if ( ! wp_verify_nonce( $_POST['nonce'], 'wpuf_user_tabs_nonce' ) ) {
            wp_die( __( 'Security check failed', 'wpuf-pro' ) );
        }

        $user_id = absint( $_POST['user_id'] );

        if ( ! $user_id ) {
            wp_send_json_error( [ 'message' => __( 'Invalid user ID', 'wpuf-pro' ) ] );
        }

        $user = get_user_by( 'ID', $user_id );
        if ( ! $user ) {
            wp_send_json_error( [ 'message' => __( 'User not found', 'wpuf-pro' ) ] );
        }

        // Activity tab content is handled elsewhere via hooks; nothing to process here
        wp_send_json_success( [ 'html' => '' ] );
    }

    /**
     * Render pagination controls for AJAX responses
     *
     * @since 4.2.0
     *
     * @param int    $current_page Current page number
     * @param int    $total_pages  Total number of pages
     * @param string $param_name   URL parameter name (e.g., 'posts_page', 'comments_page')
     *
     * @return string HTML for pagination controls
     */
    private function render_pagination_controls( $current_page, $total_pages, $param_name ) {
        if ( $total_pages <= 1 ) {
            return '';
        }

        $html = '<div class="wpuf-flex wpuf-items-center wpuf-justify-center wpuf-mt-8 wpuf-gap-2">';
        
        // Previous button
        if ( $current_page > 1 ) {
            $prev_page = $current_page - 1;
            $html .= sprintf(
                '<button class="wpuf-px-3 wpuf-py-2 wpuf-text-sm wpuf-font-medium wpuf-text-gray-500 wpuf-bg-white wpuf-border wpuf-border-gray-300 wpuf-rounded-md wpuf-hover:bg-gray-50 wpuf-hover:text-gray-700" data-page="%d" data-param="%s">%s</button>',
                $prev_page,
                esc_attr( $param_name ),
                esc_html__( 'Previous', 'wpuf-pro' )
            );
        }

        // Page numbers
        $start_page = max( 1, $current_page - 2 );
        $end_page = min( $total_pages, $current_page + 2 );

        if ( $start_page > 1 ) {
            $html .= sprintf(
                '<button class="wpuf-px-3 wpuf-py-2 wpuf-text-sm wpuf-font-medium wpuf-text-gray-500 wpuf-bg-white wpuf-border wpuf-border-gray-300 wpuf-rounded-md wpuf-hover:bg-gray-50 wpuf-hover:text-gray-700" data-page="1" data-param="%s">1</button>',
                esc_attr( $param_name )
            );
            if ( $start_page > 2 ) {
                $html .= '<span class="wpuf-px-3 wpuf-py-2 wpuf-text-sm wpuf-text-gray-500">...</span>';
            }
        }

        for ( $i = $start_page; $i <= $end_page; $i++ ) {
            if ( $i === $current_page ) {
                $html .= sprintf(
                    '<span class="wpuf-px-3 wpuf-py-2 wpuf-text-sm wpuf-font-medium wpuf-text-white wpuf-bg-indigo-600 wpuf-border wpuf-border-indigo-600 wpuf-rounded-md">%d</span>',
                    $i
                );
            } else {
                $html .= sprintf(
                    '<button class="wpuf-px-3 wpuf-py-2 wpuf-text-sm wpuf-font-medium wpuf-text-gray-500 wpuf-bg-white wpuf-border wpuf-border-gray-300 wpuf-rounded-md wpuf-hover:bg-gray-50 wpuf-hover:text-gray-700" data-page="%d" data-param="%s">%d</button>',
                    $i,
                    esc_attr( $param_name ),
                    $i
                );
            }
        }

        if ( $end_page < $total_pages ) {
            if ( $end_page < $total_pages - 1 ) {
                $html .= '<span class="wpuf-px-3 wpuf-py-2 wpuf-text-sm wpuf-text-gray-500">...</span>';
            }
            $html .= sprintf(
                '<button class="wpuf-px-3 wpuf-py-2 wpuf-text-sm wpuf-font-medium wpuf-text-gray-500 wpuf-bg-white wpuf-border wpuf-border-gray-300 wpuf-rounded-md wpuf-hover:bg-gray-50 wpuf-hover:text-gray-700" data-page="%d" data-param="%s">%d</button>',
                $total_pages,
                esc_attr( $param_name ),
                $total_pages
            );
        }

        // Next button
        if ( $current_page < $total_pages ) {
            $next_page = $current_page + 1;
            $html .= sprintf(
                '<button class="wpuf-px-3 wpuf-py-2 wpuf-text-sm wpuf-font-medium wpuf-text-gray-500 wpuf-bg-white wpuf-border wpuf-border-gray-300 wpuf-rounded-md wpuf-hover:bg-gray-50 wpuf-hover:text-gray-700" data-page="%d" data-param="%s">%s</button>',
                $next_page,
                esc_attr( $param_name ),
                esc_html__( 'Next', 'wpuf-pro' )
            );
        }

        $html .= '</div>';
        return $html;
    }

    /**
     * Render pagination using the template for AJAX requests
     *
     * @since 4.2.0
     *
     * @param int $current_page Current page number
     * @param int $total_pages Total number of pages
     * @param int $per_page Items per page
     * @param int $total_items Total number of items
     *
     * @return string HTML for pagination controls
     */
    private function render_pagination_template( $current_page, $total_pages, $per_page, $total_items ) {
        if ( $total_pages <= 1 ) {
            return '';
        }

        // Prepare pagination data for template
        $pagination = [
            'total_pages'  => $total_pages,
            'current_page' => $current_page,
            'per_page'     => $per_page,
            'total_items'  => $total_items,
        ];

        // Set up URL builder for AJAX context
        $GLOBALS['wpuf_pagination_url_builder'] = [ $this, 'build_ajax_pagination_url' ];

        // Start output buffering to capture template
        ob_start();
        include WPUF_UD_TEMPLATES . '/blocks/user-directory/components/pagination.php';
        $pagination_html = ob_get_clean();

        return $pagination_html;
    }

    /**
     * Load user posts for the standalone Posts block
     *
     * @since 4.2.0
     */
    public function load_user_posts_block() {
        // Verify nonce
        if ( ! wp_verify_nonce( $_POST['nonce'], 'wpuf_user_tabs_nonce' ) ) {
            wp_die( __( 'Security check failed', 'wpuf-pro' ) );
        }

        $user_id = absint( $_POST['user_id'] );
        $posts_per_page = absint( $_POST['posts_per_page'] ) ?: 10;
        $post_type = sanitize_text_field( $_POST['post_type'] ) ?: 'post';
        $current_page = absint( $_POST['current_page'] ) ?: 1;
        $show_pagination = $_POST['show_pagination'] === 'true';

        if ( ! $user_id ) {
            wp_send_json_error( [ 'message' => __( 'Invalid user ID', 'wpuf-pro' ) ] );
        }

        $user = get_user_by( 'ID', $user_id );
        if ( ! $user ) {
            wp_send_json_error( [ 'message' => __( 'User not found', 'wpuf-pro' ) ] );
        }

        // Use WP_Query for pagination support
        $posts_query = new \WP_Query( [
            'author'         => $user_id,
            'post_type'      => $post_type,
            'post_status'    => 'publish',
            'posts_per_page' => $posts_per_page,
            'paged'          => $current_page,
            'orderby'        => 'date',
            'order'          => 'DESC',
        ] );

        $posts = $posts_query->posts;
        $total_posts = $posts_query->found_posts;
        $total_pages = $posts_query->max_num_pages;

        if ( empty( $posts ) ) {
            wp_send_json_error( [ 'message' => __( 'No posts found', 'wpuf-pro' ) ] );
        }

        // Generate HTML using the same template structure as the tabs
        $html = '<div class="wpuf-overflow-hidden wpuf-shadow wpuf-outline wpuf-outline-1 wpuf-outline-black/5 wpuf-rounded-lg wpuf-dark:shadow-none wpuf-dark:-outline-offset-1 wpuf-dark:outline-white/10">';
        $html .= '<table class="wpuf-relative wpuf-min-w-full wpuf-divide-y wpuf-divide-gray-300 wpuf-dark:divide-white/15">';

        // Table header
        $html .= '<thead class="wpuf-bg-gray-50 wpuf-dark:bg-gray-800/75">';
        $html .= '<tr>';
        $html .= '<th scope="col" class="wpuf-py-3.5 wpuf-pr-3 wpuf-pl-4 wpuf-text-left wpuf-text-sm wpuf-font-semibold wpuf-text-gray-900 wpuf-sm:pl-6 wpuf-dark:text-gray-200">';
        $html .= esc_html__( 'Post Title', 'wpuf-pro' );
        $html .= '</th>';
        $html .= '<th scope="col" class="wpuf-px-3 wpuf-py-3.5 wpuf-text-left wpuf-text-sm wpuf-font-semibold wpuf-text-gray-900 wpuf-dark:text-gray-200">';
        $html .= esc_html__( 'Publish Date', 'wpuf-pro' );
        $html .= '</th>';
        $html .= '<th scope="col" class="wpuf-py-3.5 wpuf-pr-4 wpuf-pl-3 wpuf-sm:pr-6">';
        $html .= '<span class="wpuf-sr-only">' . esc_html__( 'View', 'wpuf-pro' ) . '</span>';
        $html .= '</th>';
        $html .= '</tr>';
        $html .= '</thead>';

        // Table body
        $html .= '<tbody class="wpuf-divide-y wpuf-divide-gray-200 wpuf-bg-white wpuf-dark:divide-white/10 wpuf-dark:bg-gray-800/50">';

        foreach ( $posts as $post ) {
            $html .= '<tr>';
            $html .= '<td class="wpuf-py-4 wpuf-pr-3 wpuf-pl-4 wpuf-text-sm wpuf-font-medium wpuf-whitespace-nowrap wpuf-text-gray-900 wpuf-sm:pl-6 wpuf-dark:text-white">';
            $html .= esc_html( get_the_title( $post->ID ) );
            $html .= '</td>';
            $html .= '<td class="wpuf-px-3 wpuf-py-4 wpuf-text-sm wpuf-whitespace-nowrap wpuf-text-gray-500 wpuf-dark:text-gray-400">';
            $html .= esc_html( get_the_date( 'F j, Y', $post->ID ) );
            $html .= '</td>';
            $html .= '<td class="wpuf-py-4 wpuf-pr-4 wpuf-pl-3 wpuf-text-right wpuf-text-sm wpuf-font-medium wpuf-whitespace-nowrap wpuf-sm:pr-6">';
            $html .= '<a href="' . esc_url( get_permalink( $post->ID ) ) . '" class="wpuf-text-indigo-600 wpuf-hover:text-indigo-900 wpuf-dark:text-indigo-400 wpuf-dark:hover:text-indigo-300">';
            $html .= esc_html__( 'Link ->', 'wpuf-pro' );
            $html .= '<span class="wpuf-sr-only">, ' . esc_html( get_the_title( $post->ID ) ) . '</span>';
            $html .= '</a>';
            $html .= '</td>';
            $html .= '</tr>';
        }

        $html .= '</tbody>';
        $html .= '</table>';
        $html .= '</div>';

        // Add pagination if enabled and there are multiple pages
        $pagination_html = '';
        if ( $show_pagination && $total_pages > 1 ) {
            $pagination_html = $this->render_pagination_template( $current_page, $total_pages, $posts_per_page, $total_posts );
        }

        wp_send_json_success( [ 
            'html' => $html,
            'pagination' => $pagination_html,
            'pagination_data' => [
                'current_page' => $current_page,
                'total_pages' => $total_pages,
                'total_posts' => $total_posts,
                'posts_per_page' => $posts_per_page
            ]
        ] );
    }

    /**
     * Load user comments for the standalone Comments block
     *
     * @since 4.2.0
     */
    public function load_user_comments_block() {
        // Verify nonce
        if ( ! wp_verify_nonce( $_POST['nonce'], 'wpuf_user_tabs_nonce' ) ) {
            wp_die( __( 'Security check failed', 'wpuf-pro' ) );
        }

        $user_id = absint( $_POST['user_id'] );
        $comments_per_page = absint( $_POST['comments_per_page'] ) ?: 10;
        $post_type = sanitize_text_field( $_POST['post_type'] ) ?: 'post';
        $current_page = absint( $_POST['current_page'] ) ?: 1;
        $show_pagination = $_POST['show_pagination'] === 'true';

        if ( ! $user_id ) {
            wp_send_json_error( [ 'message' => __( 'Invalid user ID', 'wpuf-pro' ) ] );
        }

        $user = get_user_by( 'ID', $user_id );
        if ( ! $user ) {
            wp_send_json_error( [ 'message' => __( 'User not found', 'wpuf-pro' ) ] );
        }

        // Calculate offset for pagination
        $offset = ( $current_page - 1 ) * $comments_per_page;

        // Get total comments count first for pagination
        $total_comments_args = [
            'user_id' => $user_id,
            'status'  => 'approve',
            'count'   => true
        ];

        // Filter by post type if specified
        if ( $post_type && $post_type !== 'all' ) {
            $post_ids = get_posts( [
                'post_type'      => $post_type,
                'post_status'    => 'publish',
                'fields'         => 'ids',
                'posts_per_page' => -1,
            ] );
            if ( ! empty( $post_ids ) ) {
                $total_comments_args['post__in'] = $post_ids;
            } else {
                // No posts of this type, return empty
                wp_send_json_error( [ 'message' => __( 'No comments found', 'wpuf-pro' ) ] );
            }
        }

        $total_comments = get_comments( $total_comments_args );

        // Build comments query with pagination
        $comments_args = [
            'user_id' => $user_id,
            'number'  => $comments_per_page,
            'offset'  => $offset,
            'status'  => 'approve',
            'orderby' => 'comment_date',
            'order'   => 'DESC',
        ];

        // Apply post type filter to comments query
        if ( $post_type && $post_type !== 'all' && ! empty( $post_ids ) ) {
            $comments_args['post__in'] = $post_ids;
        }

        $comments = get_comments( $comments_args );

        if ( empty( $comments ) ) {
            wp_send_json_error( [ 'message' => __( 'No comments found', 'wpuf-pro' ) ] );
        }

        // Generate HTML using the same template structure as the tabs
        $html = '<div class="wpuf-overflow-hidden wpuf-shadow wpuf-outline wpuf-outline-1 wpuf-outline-black/5 wpuf-rounded-lg wpuf-dark:shadow-none wpuf-dark:-outline-offset-1 wpuf-dark:outline-white/10">';
        $html .= '<div class="wpuf-divide-y wpuf-divide-gray-200 wpuf-bg-white wpuf-dark:divide-white/10 wpuf-dark:bg-gray-800/50">';

        foreach ( $comments as $comment ) {
            $comment_content = wp_strip_all_tags( $comment->comment_content );
            $comment_excerpt = wp_trim_words( $comment_content, 20, '...' );
            $comment_date    = date_i18n( 'M j, Y', strtotime( $comment->comment_date ) );
            $post_title     = get_the_title( $comment->comment_post_ID );
            $post_url       = get_permalink( $comment->comment_post_ID );
            $reply_count    = get_comments( [
                'parent' => $comment->comment_ID,
                'count'  => true,
            ] );

            $html .= sprintf(
                '<div class="wpuf-px-4 wpuf-py-4">
                    <div class="wpuf-flex wpuf-items-start wpuf-gap-3">
                        <div class="wpuf-flex-shrink-0">
                            <div class="wpuf-w-8 wpuf-h-8 wpuf-bg-gray-200 wpuf-dark:bg-gray-700 wpuf-rounded-full wpuf-flex wpuf-items-center wpuf-justify-center">
                                <span class="wpuf-text-xs wpuf-font-medium wpuf-text-gray-600 wpuf-dark:text-gray-300">%s</span>
                            </div>
                        </div>
                        <div class="wpuf-flex-1 wpuf-min-w-0">
                            <div class="wpuf-flex wpuf-items-center wpuf-gap-2 wpuf-mb-1">
                                <span class="wpuf-text-sm wpuf-font-medium wpuf-text-gray-900 wpuf-dark:text-white">%s</span>
                                <span class="wpuf-text-xs wpuf-text-gray-500 wpuf-dark:text-gray-400">%s</span>
                            </div>
                            <p class="wpuf-text-sm wpuf-text-gray-700 wpuf-dark:text-gray-300 wpuf-mb-2">%s</p>
                            <div class="wpuf-flex wpuf-items-center wpuf-gap-4 wpuf-text-xs wpuf-text-gray-500 wpuf-dark:text-gray-400">
                                <span>%s: <a href="%s" class="wpuf-text-indigo-600 wpuf-hover:text-indigo-900 wpuf-dark:text-indigo-400 wpuf-dark:hover:text-indigo-300">%s</a></span>%s
                            </div>
                        </div>
                    </div>
                </div>',
                esc_html( strtoupper( substr( $user->display_name, 0, 1 ) ) ),
                esc_html( $user->display_name ),
                esc_html( $comment_date ),
                esc_html( $comment_excerpt ),
                esc_html__( 'On', 'wpuf-pro' ),
                esc_url( $post_url ),
                esc_html( $post_title ),
                $reply_count > 0 ? sprintf( '<span>%d %s</span>', $reply_count, esc_html__( 'replies', 'wpuf-pro' ) ) : ''
            );
        }

        $html .= '</div>';
        $html .= '</div>';

        // Add pagination if enabled and there are multiple pages
        $pagination_html = '';
        $total_pages = ceil( $total_comments / $comments_per_page );
        if ( $show_pagination && $total_pages > 1 ) {
            $pagination_html = $this->render_pagination_template( $current_page, $total_pages, $comments_per_page, $total_comments );
        }

        wp_send_json_success( [ 
            'html' => $html,
            'pagination' => $pagination_html,
            'pagination_data' => [
                'current_page' => $current_page,
                'total_pages' => $total_pages,
                'total_comments' => $total_comments,
                'comments_per_page' => $comments_per_page
            ]
        ] );
    }

    /**
     * Build pagination URL for AJAX context
     *
     * @since 4.2.0
     *
     * @param string $base_url Base URL
     * @param array  $query_args Query arguments
     * @param int    $page Page number
     *
     * @return string Pagination URL
     */
    public function build_ajax_pagination_url( $base_url, $query_args, $page ) {
        // For AJAX context, we don't need real URLs since JavaScript will handle clicks
        // Return a placeholder that JavaScript can extract the page number from
        return '#page-' . $page;
    }


}
