/**
 * WPUF User Tabs Frontend JavaScript
 * Handles tab switching, content loading, and dynamic functionality
 */

(function($) {
    'use strict';

    class WPUFUserTabs {
        constructor(container) {
            this.container = $(container);
            this.tabConfig = this.getTabConfig();
            this.currentTab = this.container.data('default-tab') || 'about';
            this.userId = this.container.data('user-id');

            this.init();
        }

        /**
         * Get tab configuration from the block
         */
        getTabConfig() {
            const configScript = this.container.find('.wpuf-tab-config');
            if (configScript.length) {
                try {
                    return JSON.parse(configScript.html());
                } catch (e) {
                    console.warn('Failed to parse tab config:', e);
                }
            }
            return [];
        }

        /**
         * Initialize the tabs
         */
        init() {
            this.setInitialTab();
            this.bindEvents();
            this.setupMobileDropdown();

            // Ensure initial tab link state reflects currentTab
            const $nav = this.container.find('nav');
            const activeClasses = 'wpuf-border-current wpuf-text-current';
            const inactiveClasses = 'wpuf-border-transparent wpuf-text-gray-500 hover:wpuf-border-gray-300 hover:wpuf-text-gray-700';
            const $links = $nav.find('[data-tab-id]');
            $links.removeClass(activeClasses).removeClass(inactiveClasses).addClass(inactiveClasses);
            $nav.find(`[data-tab-id="${this.currentTab}"]`).removeClass(inactiveClasses).addClass(activeClasses);

            // Show the current tab panel and load content
            const $panels = this.container.find('.wpuf-tab-content-area .wpuf-tab-content');
            $panels.addClass('wpuf-hidden').removeClass('wpuf-tab-active');
            const $currentPanel = this.container.find(`.wpuf-tab-content-area .wpuf-tab-content[data-tab-id="${this.currentTab}"]`);
            $currentPanel.removeClass('wpuf-hidden').addClass('wpuf-tab-active');
            this.loadTabContent(this.currentTab, $currentPanel);
        }

        /**
         * Set the initial active tab
         */
        setInitialTab() {
            // Get query parameters from URL
            const urlParams = new URLSearchParams(window.location.search);
            const cpage = urlParams.get('cpage');
            const tab = urlParams.get('tab');

            // Check if cpage or tab query parameters are present
            if (cpage !== null || tab !== null) {
                // Set active tab based on tab query parameter
                if (tab !== null && tab !== '') {
                    this.currentTab = tab;
                }
            }
        }

        /**
         * Bind event handlers
         */
        bindEvents() {
            // Tab clicks (anchors with data-tab-id)
            this.container.on('click', '[data-tab-id]', (e) => {
                // Only handle clicks from tab nav links
                const $target = $(e.currentTarget);
                if ($target.closest('nav').length === 0) {
                    return;
                }
                e.preventDefault();
                const tabId = $target.data('tab-id');
                if (tabId) {
                    this.switchTab(tabId);
                }
            });

            // Keyboard navigation on tab links
            this.container.on('keydown', '[data-tab-id]', (e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                    if ($(e.currentTarget).closest('nav').length) {
                        e.preventDefault();
                        $(e.currentTarget).trigger('click');
                    }
                }
            });
        }

        /**
         * Setup mobile dropdown functionality
         */
        setupMobileDropdown() {
            const dropdown = this.container.find('select');
            if (dropdown.length) {
                dropdown.val(this.currentTab);
                dropdown.on('change', (e) => {
                    const tabId = $(e.currentTarget).val();
                    if (tabId) {
                        this.switchTab(tabId);
                    }
                });
            }
        }

        /**
         * Switch to a specific tab
         */
        switchTab(tabId) {
            // Update active states for tab links and classes
            const $nav = this.container.find('nav');
            const activeClasses = 'wpuf-border-current wpuf-text-current';
            const inactiveClasses = 'wpuf-border-transparent wpuf-text-gray-500 hover:wpuf-border-gray-300 hover:wpuf-text-gray-700';

            const $links = $nav.find('[data-tab-id]');
            $links
                .removeClass('wpuf-tab-active')
                .attr('aria-selected', 'false')
                .removeClass(activeClasses)
                .removeClass(inactiveClasses)
                .addClass(inactiveClasses);

            const $activeLink = $nav.find(`[data-tab-id="${tabId}"]`);
            $activeLink
                .addClass('wpuf-tab-active')
                .attr('aria-selected', 'true')
                .removeClass(inactiveClasses)
                .addClass(activeClasses);

            // Hide all tab panels
            const $panels = this.container.find('.wpuf-tab-content-area .wpuf-tab-content');
            $panels.addClass('wpuf-hidden').removeClass('wpuf-tab-active');

            // Show selected tab panel
            const targetPanel = this.container.find(`.wpuf-tab-content-area .wpuf-tab-content[data-tab-id="${tabId}"]`);
            targetPanel.removeClass('wpuf-hidden').addClass('wpuf-tab-active');

            // Load tab content if needed
            this.loadTabContent(tabId, targetPanel);

            // Update current tab
            this.currentTab = tabId;

            // Trigger custom event
            this.container.trigger('wpuf:tab-switched', [tabId]);
        }

        /**
         * Load content for a specific tab
         */
        loadTabContent(tabId, tabPanel = null) {
            const tabContent = (tabPanel && tabPanel.length)
                ? tabPanel
                : this.container.find(`.wpuf-tab-content-area .wpuf-tab-content[data-tab-id="${tabId}"]`);

            if (!tabContent || !tabContent.length) {
                return;
            }

            // Don't reload if content is already loaded
            if (tabContent.find('.wpuf-tab-loaded').length || tabContent.hasClass('wpuf-tab-loaded')) {
                return;
            }

            // Load content based on tab type
            switch (tabId) {
                case 'about':
                    // About tab content is already loaded via InnerBlocks
                    tabContent.addClass('wpuf-tab-loaded');
                    break;

                case 'posts':
                    this.loadPostsTab(tabContent);
                    break;

                case 'comments':
                    this.loadCommentsTab(tabContent);
                    break;

                case 'files':
                    this.loadFilesTab(tabContent);
                    break;

                case 'activity':
                    this.loadActivityTab(tabContent);
                    break;

                default:
                    tabContent.html('<div class="wpuf-tab-empty">No content available for this tab.</div>');
                    tabContent.addClass('wpuf-tab-loaded');
                    break;
            }
        }

        /**
         * Bind pagination click handlers for a tab content
         */
        bindPaginationHandlers(tabContent, tabType) {
            const self = this;
            
            // Remove existing handlers to prevent duplicates
            tabContent.off('click.pagination');
            
            // Bind new pagination handlers for template-generated links
            tabContent.on('click.pagination', 'a.wpuf-pagination-link', function(e) {
                e.preventDefault();
                const href = $(this).attr('href');
                const page = self.extractPageFromHref(href);
                
                if (page && page > 0) {
                    // Load the new page content
                    if (tabType === 'posts') {
                        self.loadPostsTab(tabContent, page);
                    } else if (tabType === 'comments') {
                        self.loadCommentsTab(tabContent, page);
                    }
                }
            });
        }

        /**
         * Extract page number from href attribute
         */
        extractPageFromHref(href) {
            // Handle AJAX pagination URLs like "#page-2"
            const ajaxMatch = href.match(/#page-(\d+)/);
            if (ajaxMatch) {
                return parseInt(ajaxMatch[1]);
            }
            
            // Handle regular URLs with page parameter
            try {
                const url = new URL(href, window.location.origin);
                const page = url.searchParams.get('page');
                return page ? parseInt(page) : 1;
            } catch (e) {
                return 1;
            }
        }

        /**
         * Load posts tab content
         */
        loadPostsTab(tabContent, page = 1) {
            const postsPerPage = this.container.data('posts-per-page') || 10;
            const showPagination = this.container.data('show-posts-pagination') === true;
            const showExcerpts = this.container.data('show-excerpts') === 'true';
            const self = this; // Store reference to this
            

            // Show loading state
            tabContent.addClass('wpuf-tab-loading');

            $.ajax({
                url: wpufUserTabs.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'wpuf_load_user_posts',
                    user_id: this.userId,
                    posts_per_page: postsPerPage,
                    show_excerpts: showExcerpts,
                    current_page: page,
                    show_pagination: showPagination ? 'true' : 'false',
                    nonce: wpufUserTabs.nonce
                },
                success: function(response) {
                    tabContent.removeClass('wpuf-tab-loading');
                    if (response.success) {
                        let html = response.data.html;
                        if (response.data.pagination) {
                            html += response.data.pagination;
                        }
                        tabContent.html(html);
                        tabContent.addClass('wpuf-tab-loaded');
                        
                        // Store pagination data for future use
                        tabContent.data('pagination-data', response.data.pagination_data);
                        
                        // Bind pagination click handlers
                        self.bindPaginationHandlers(tabContent, 'posts');
                    } else {
                        tabContent.html('<div class="wpuf-tab-empty">No posts found.</div>');
                    }
                },
                error: function() {
                    tabContent.removeClass('wpuf-tab-loading');
                    tabContent.html('<div class="wpuf-tab-error">Failed to load posts.</div>');
                }
            });
        }

        /**
         * Load comments tab content
         */
        loadCommentsTab(tabContent, page = 1) {
            const commentsPerPage = this.container.data('comments-per-page') || 10;
            const showPagination = this.container.data('show-comments-pagination') === true;
            const commentLength = this.container.data('comment-length') || 100;
            const self = this; // Store reference to this

            // Show loading state
            tabContent.addClass('wpuf-tab-loading');

            $.ajax({
                url: wpufUserTabs.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'wpuf_load_user_comments',
                    user_id: this.userId,
                    comment_length: commentLength,
                    comments_per_page: commentsPerPage,
                    current_page: page,
                    show_pagination: showPagination ? 'true' : 'false',
                    nonce: wpufUserTabs.nonce
                },
                success: function(response) {
                    tabContent.removeClass('wpuf-tab-loading');
                    if (response.success) {
                        let html = response.data.html;
                        if (response.data.pagination) {
                            html += response.data.pagination;
                        }
                        tabContent.html(html);
                        tabContent.addClass('wpuf-tab-loaded');
                        
                        // Store pagination data for future use
                        tabContent.data('pagination-data', response.data.pagination_data);
                        
                        // Bind pagination click handlers
                        self.bindPaginationHandlers(tabContent, 'comments');
                    } else {
                        tabContent.html('<div class="wpuf-tab-empty">No comments found.</div>');
                    }
                },
                error: function() {
                    tabContent.removeClass('wpuf-tab-loading');
                    tabContent.html('<div class="wpuf-tab-error">Failed to load comments.</div>');
                }
            });
        }

        /**
         * Load files tab content
         */
        loadFilesTab(tabContent) {
            // Show loading state
            tabContent.addClass('wpuf-tab-loading');

            $.ajax({
                url: wpufUserTabs.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'wpuf_load_user_files',
                    user_id: this.userId,
                    nonce: wpufUserTabs.nonce
                },
                success: (response) => {
                    tabContent.removeClass('wpuf-tab-loading');
                    if (response.success) {
                        tabContent.html(response.data.html);
                        tabContent.addClass('wpuf-tab-loaded');

                        // Trigger event for dynamically loaded content
                        $(document).trigger('wpuf:tab-content-loaded', [tabContent]);
                    } else {
                        tabContent.html('<div class="wpuf-tab-empty">No files found.</div>');
                    }
                },
                error: () => {
                    tabContent.removeClass('wpuf-tab-loading');
                    tabContent.html('<div class="wpuf-tab-error">Failed to load files.</div>');
                }
            });
        }

        /**
         * Load activity tab content
         */
        loadActivityTab(tabContent) {
            // Show loading state
            tabContent.addClass('wpuf-tab-loading');

            $.ajax({
                url: wpufUserTabs.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'wpuf_load_user_activity',
                    user_id: this.userId,
                    nonce: wpufUserTabs.nonce
                },
                success: (response) => {
                    tabContent.removeClass('wpuf-tab-loading');
                    if (response && response.success && response.data && response.data.html) {
                        tabContent.html(response.data.html);
                        tabContent.addClass('wpuf-tab-loaded');
                    } else {
                        const message = (response && response.data && response.data.message) ? response.data.message : 'No activity found.';
                        tabContent.html('<div class="wpuf-tab-empty">' + message + '</div>');
                        tabContent.addClass('wpuf-tab-loaded');
                    }
                },
                error: () => {
                    tabContent.removeClass('wpuf-tab-loading');
                    tabContent.html('<div class="wpuf-tab-error">Failed to load activity.</div>');
                }
            });
        }
    }

    /**
     * WPUF File Tabs Handler
     * Handles file type tabs within user profile sections
     */
    class WPUFFileTabs {
        constructor(container) {
            this.container = $(container);
            this.activeTab = null;
            this.init();
        }

        /**
         * Initialize file tabs
         */
        init() {
            this.bindEvents();
            this.setInitialTab();
        }

        /**
         * Bind event handlers for file tabs
         */
        bindEvents() {
            this.container.on('click', '.wpuf-file-tab-btn', (e) => {
                e.preventDefault();
                const $button = $(e.currentTarget);
                const targetType = $button.data('tab');

                if (targetType) {
                    this.switchFileTab(targetType, $button);
                }
            });
        }

        /**
         * Set the initial active tab
         */
        setInitialTab() {
            // Always check which content is visible and set that tab as active
            const $visibleGroup = this.container.find('.wpuf-file-group').filter(function() {
                return $(this).css('display') !== 'none';
            }).first();

            if ($visibleGroup.length) {
                const visibleType = $visibleGroup.data('type');
                const $activeButton = this.container.find(`.wpuf-file-tab-btn[data-tab="${visibleType}"]`);
                if ($activeButton.length) {
                    this.activeTab = visibleType;
                    this.switchFileTab(this.activeTab, $activeButton);
                    return;
                }
            }

            // Fallback to first tab if no visible content found
            const $firstTabBtn = this.container.find('.wpuf-file-tab-btn').first();
            if ($firstTabBtn.length) {
                this.activeTab = $firstTabBtn.data('tab');
                this.switchFileTab(this.activeTab, $firstTabBtn);
            }
        }

        /**
         * Switch to a specific file tab
         */
        switchFileTab(targetType, $activeButton) {
            const $allButtons = this.container.find('.wpuf-file-tab-btn');
            const $allGroups = this.container.find('.wpuf-file-group');

            // Get color classes from the active button
            const activeClasses = this.getActiveClasses($activeButton);
            const inactiveClasses = this.getInactiveClasses($activeButton);

            // Update button states
            $allButtons
                .removeClass(activeClasses.active)
                .removeClass(inactiveClasses.inactive)
                .addClass(inactiveClasses.inactive)
                .removeAttr('data-active');

            $activeButton
                .removeClass(inactiveClasses.inactive)
                .addClass(activeClasses.active)
                .attr('data-active', 'true');

            // Show/hide file groups
            $allGroups.hide();
            this.container.find(`.wpuf-file-group[data-type="${targetType}"]`).show();

            this.activeTab = targetType;
        }

        /**
         * Get active color classes from button
         */
        getActiveClasses($button) {
            const classes = $button.attr('class') || '';

            // Extract active classes based on common patterns
            const activeBorderMatch = classes.match(/wpuf-border-([a-z]+)-500/);
            const activeTextMatch = classes.match(/wpuf-text-([a-z]+)-600/);

            if (activeBorderMatch && activeTextMatch) {
                const color = activeBorderMatch[1];
                return {
                    active: `wpuf-border-${color}-500 wpuf-text-${color}-600`
                };
            }

            // Fallback to default classes
            return {
                active: 'wpuf-border-gray-500 wpuf-text-gray-600'
            };
        }

        /**
         * Get inactive color classes from button
         */
        getInactiveClasses($button) {
            const classes = $button.attr('class') || '';

            // Extract inactive classes based on common patterns
            const inactiveBorderMatch = classes.match(/wpuf-border-transparent/);
            const inactiveTextMatch = classes.match(/wpuf-text-([a-z]+)-500/);
            const hoverTextMatch = classes.match(/hover:wpuf-text-([a-z]+)-700/);
            const hoverBorderMatch = classes.match(/hover:wpuf-border-([a-z]+)-300/);

            if (inactiveBorderMatch && inactiveTextMatch) {
                const color = inactiveTextMatch[1];
                const hoverText = hoverTextMatch ? `hover:wpuf-text-${color}-700` : '';
                const hoverBorder = hoverBorderMatch ? `hover:wpuf-border-${color}-300` : '';

                return {
                    inactive: `wpuf-border-transparent wpuf-text-${color}-500 ${hoverText} ${hoverBorder}`.trim()
                };
            }

            // Fallback to default classes
            return {
                inactive: 'wpuf-border-transparent wpuf-text-gray-500 hover:wpuf-text-gray-700 hover:wpuf-border-gray-300'
            };
        }

    }

    /**
     * WPUF User Posts Class
     * Handles AJAX pagination for standalone User Posts blocks
     */
    class WPUFUserPosts {
        constructor(container) {
            this.container = $(container);
            this.userId = this.container.data('user-id');
            this.postsPerPage = this.container.data('posts-per-page') || 10;
            this.postType = this.container.data('post-type') || 'post';
            // Handle different possible values for show-pagination
            const showPaginationValue = this.container.data('show-pagination');
            this.showPagination = showPaginationValue === true || showPaginationValue === 'true' || showPaginationValue === 1 || showPaginationValue === '1';
            this.currentPage = this.container.data('current-page') || 1;
            this.totalPages = this.container.data('total-pages') || 1;
            this.init();
        }

        /**
         * Initialize the User Posts block
         */
        init() {
            this.bindPaginationHandlers();
        }

        /**
         * Bind pagination click handlers
         */
        bindPaginationHandlers() {
            const self = this;
            
            // Remove existing handlers to prevent duplicates
            this.container.off('click.pagination');
            
            // Bind new pagination handlers
            this.container.on('click.pagination', 'a.wpuf-pagination-link', function(e) {
                e.preventDefault();
                const href = $(this).attr('href');
                const page = self.extractPageFromHref(href);
                
                if (page && page > 0 && page !== self.currentPage) {
                    self.loadPage(page);
                }
            });
        }

        /**
         * Extract page number from href
         */
        extractPageFromHref(href) {
            if (!href || href === '#') {
                return 1;
            }
            
            try {
                // Handle AJAX pagination hrefs like "#page-2"
                if (href.startsWith('#page-')) {
                    return parseInt(href.replace('#page-', ''));
                }
                
                // Handle URL parameters like "?posts_page=2"
                const url = new URL(href, window.location.origin);
                const postsPage = url.searchParams.get('posts_page');
                if (postsPage) {
                    return parseInt(postsPage);
                }
                
                return 1;
            } catch (e) {
                return 1;
            }
        }

        /**
         * Load a specific page via AJAX
         */
        loadPage(page) {
            const self = this;
            
            // Show loading state
            this.container.addClass('wpuf-loading');
            
            $.ajax({
                url: wpufUserTabs.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'wpuf_load_user_posts_block',
                    user_id: this.userId,
                    posts_per_page: this.postsPerPage,
                    post_type: this.postType,
                    current_page: page,
                    show_pagination: this.showPagination ? 'true' : 'false',
                    nonce: wpufUserTabs.nonce
                },
                success: function(response) {
                    self.container.removeClass('wpuf-loading');
                    if (response.success) {
                        // Update the container with new content
                        let html = response.data.html;
                        if (response.data.pagination) {
                            html += response.data.pagination;
                        }
                        
                        self.container.html(html);
                        
                        // Update current page
                        self.currentPage = page;
                        
                        // Re-bind pagination handlers for new content
                        self.bindPaginationHandlers();
                        
                        // Scroll to top of posts block
                        self.container[0].scrollIntoView({ behavior: 'smooth', block: 'start' });
                    } else {
                        self.container.html('<div class="wpuf-posts-error">' + (response.data.message || 'Failed to load posts') + '</div>');
                    }
                },
                error: function(xhr, status, error) {
                    self.container.removeClass('wpuf-loading');
                    self.container.html('<div class="wpuf-posts-error">Failed to load posts. Please try again.</div>');
                }
            });
        }
    }

    /**
     * WPUF User Comments Class
     * Handles AJAX pagination for standalone User Comments blocks
     */
    class WPUFUserComments {
        constructor(container) {
            this.container = $(container);
            this.userId = this.container.data('user-id');
            this.commentsPerPage = this.container.data('comments-per-page') || 10;
            this.postType = this.container.data('post-type') || 'post';
            // Handle different possible values for show-pagination
            const showPaginationValue = this.container.data('show-pagination');
            this.showPagination = showPaginationValue === true || showPaginationValue === 'true' || showPaginationValue === 1 || showPaginationValue === '1';
            this.currentPage = this.container.data('current-page') || 1;
            this.totalPages = this.container.data('total-pages') || 1;

            this.init();
        }

        /**
         * Initialize the User Comments block
         */
        init() {
            this.bindPaginationHandlers();
        }

        /**
         * Bind pagination click handlers
         */
        bindPaginationHandlers() {
            const self = this;
            
            // Remove existing handlers to prevent duplicates
            this.container.off('click.pagination');
            
            // Bind new pagination handlers
            this.container.on('click.pagination', 'a.wpuf-pagination-link', function(e) {
                e.preventDefault();
                const href = $(this).attr('href');
                const page = self.extractPageFromHref(href);
                
                if (page && page > 0 && page !== self.currentPage) {
                    self.loadPage(page);
                }
            });
        }

        /**
         * Extract page number from href
         */
        extractPageFromHref(href) {
            if (!href || href === '#') {
                return 1;
            }
            
            try {
                // Handle AJAX pagination hrefs like "#page-2"
                if (href.startsWith('#page-')) {
                    return parseInt(href.replace('#page-', ''));
                }
                
                // Handle URL parameters like "?comments_page=2"
                const url = new URL(href, window.location.origin);
                const commentsPage = url.searchParams.get('comments_page');
                if (commentsPage) {
                    return parseInt(commentsPage);
                }
                
                return 1;
            } catch (e) {
                return 1;
            }
        }

        /**
         * Load a specific page via AJAX
         */
        loadPage(page) {
            const self = this;
            
            // Show loading state
            this.container.addClass('wpuf-loading');
            
            $.ajax({
                url: wpufUserTabs.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'wpuf_load_user_comments_block',
                    user_id: this.userId,
                    comments_per_page: this.commentsPerPage,
                    post_type: this.postType,
                    current_page: page,
                    show_pagination: this.showPagination ? 'true' : 'false',
                    nonce: wpufUserTabs.nonce
                },
                success: function(response) {
                    self.container.removeClass('wpuf-loading');
                    if (response.success) {
                        // Update the container with new content
                        let html = response.data.html;
                        if (response.data.pagination) {
                            html += response.data.pagination;
                        }
                        
                        self.container.html(html);
                        
                        // Update current page
                        self.currentPage = page;
                        
                        // Re-bind pagination handlers for new content
                        self.bindPaginationHandlers();
                        
                        // Scroll to top of comments block
                        self.container[0].scrollIntoView({ behavior: 'smooth', block: 'start' });
                    } else {
                        self.container.html('<div class="wpuf-comments-error">' + (response.data.message || 'Failed to load comments') + '</div>');
                    }
                },
                error: function(xhr, status, error) {
                    self.container.removeClass('wpuf-loading');
                    self.container.html('<div class="wpuf-comments-error">Failed to load comments. Please try again.</div>');
                }
            });
        }
    }

    // Initialize tabs when DOM is ready
    $(document).ready(function() {
        // Initialize user tabs
        $('.wpuf-user-tabs').each(function() {
            new WPUFUserTabs(this);
        });

        // Initialize file tabs
        $('.wpuf-files-section').each(function() {
            new WPUFFileTabs(this);
        });
        
        // Initialize User Posts blocks for AJAX pagination
        $('.wpuf-user-posts').each(function() {
            new WPUFUserPosts(this);
        });

        // Initialize User Comments blocks for AJAX pagination
        $('.wpuf-user-comments').each(function() {
            new WPUFUserComments(this);
        });
    });

    // Handle dynamically loaded content (for AJAX-loaded tabs)
    $(document).on('wpuf:tab-content-loaded', function(e, tabContent) {
        // Re-initialize file tabs for newly loaded content
        $(tabContent).find('.wpuf-files-section').each(function() {
            new WPUFFileTabs(this);
        });
        
        // Re-initialize user posts blocks for newly loaded content
        $(tabContent).find('.wpuf-user-posts').each(function() {
            new WPUFUserPosts(this);
        });
        
        // Re-initialize user comments blocks for newly loaded content
        $(tabContent).find('.wpuf-user-comments').each(function() {
            new WPUFUserComments(this);
        });
    });

    // Make classes available globally for potential external use
    window.WPUFUserTabs = WPUFUserTabs;
    window.WPUFFileTabs = WPUFFileTabs;
    window.WPUFUserPosts = WPUFUserPosts;
    window.WPUFUserComments = WPUFUserComments;

})(jQuery);
