/**
 * Common Tabs JavaScript for AI Auto Tool Plugin
 * Used across all features with tabbed interface
 * All functions prefixed with 'aiautotool' for consistency
 */
(function($) {
    'use strict';

    /**
     * AI Auto Tool Tabs Manager
     */
    const AiautotoolTabs = {
        /**
         * Initialize tabs functionality
         */
        init: function() {
            this.bindEvents();
            this.initAllTabs();
        },

        /**
         * Bind click events to tab buttons
         */
        bindEvents: function() {
            $(document).on('click', '.aiautotool-tab-btn', this.handleTabSwitch);
        },
        
        /**
         * Initialize all tab containers on page
         */
        initAllTabs: function() {
            // Find all tab containers
            $('.aiautotool-tabs-nav').each(function() {
                const $container = $(this).closest('[id^="tab-"]');
                if ($container.length) {
                    const containerId = $container.attr('id');
                    const savedTab = AiautotoolTabs.getSavedTab(containerId);
                    
                    if (savedTab) {
                        AiautotoolTabs.switchTab(containerId, savedTab);
                    } else {
                        // Ensure first tab is active if no saved tab
                        const $firstBtn = $container.find('.aiautotool-tab-btn').first();
                        if ($firstBtn.length && !$container.find('.aiautotool-tab-btn.active').length) {
                            const firstTabId = $firstBtn.data('tab');
                            if (firstTabId) {
                                AiautotoolTabs.switchTab(containerId, firstTabId);
                            }
                        }
                    }
                }
            });
            
            // Also initialize tabs when containers become visible
            // This handles cases where tabs are in hidden containers initially
            // Use MutationObserver to watch for display changes
            const observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
                        const $target = $(mutation.target);
                        if ($target.hasClass('tab-content') && $target.is(':visible')) {
                            // Container became visible, initialize tabs inside it
                            if ($target.find('.aiautotool-tabs-nav').length) {
                                setTimeout(function() {
                                    const $container = $target.find('.aiautotool-tabs-nav').closest('[id^="tab-"]');
                                    if ($container.length) {
                                        const containerId = $container.attr('id');
                                        const savedTab = AiautotoolTabs.getSavedTab(containerId);
                                        
                                        if (savedTab) {
                                            AiautotoolTabs.switchTab(containerId, savedTab);
                                        } else {
                                            // Ensure first tab is active
                                            const $firstBtn = $container.find('.aiautotool-tab-btn').first();
                                            if ($firstBtn.length && !$container.find('.aiautotool-tab-btn.active').length) {
                                                const firstTabId = $firstBtn.data('tab');
                                                if (firstTabId) {
                                                    AiautotoolTabs.switchTab(containerId, firstTabId);
                                                }
                                            }
                                        }
                                    }
                                }, 50);
                            }
                        }
                    }
                });
            });
            
            // Observe all tab-content containers
            $('.tab-content').each(function() {
                observer.observe(this, {
                    attributes: true,
                    attributeFilter: ['style']
                });
            });
            
            // Also listen for clicks on main navigation tabs
            $(document).on('click', '.nav-tab.sotab', function() {
                setTimeout(function() {
                    AiautotoolTabs.initAllTabs();
                }, 100);
            });
        },
        
        /**
         * Get saved tab from localStorage
         * @param {string} containerId - The container ID
         * @returns {string|null} - Saved tab ID or null
         */
        getSavedTab: function(containerId) {
            const storageKey = 'aiautotool_tab_' + containerId;
            return localStorage.getItem(storageKey);
        },
        
        /**
         * Save tab to localStorage
         * @param {string} containerId - The container ID
         * @param {string} tabId - The tab ID to save
         */
        saveTab: function(containerId, tabId) {
            const storageKey = 'aiautotool_tab_' + containerId;
            localStorage.setItem(storageKey, tabId);
        },
        
        /**
         * Switch to a specific tab
         * @param {string} containerId - The container ID
         * @param {string} tabId - The tab ID to switch to
         */
        switchTab: function(containerId, tabId) {
            const $container = $('#' + containerId);
            
            if (!$container.length) {
                return;
            }
            
            // Update buttons
            $container.find('.aiautotool-tab-btn').removeClass('active');
            $container.find('.aiautotool-tab-btn[data-tab="' + tabId + '"]').addClass('active');
            
            // Update content
            $container.find('.aiautotool-tab-content').removeClass('active');
            $container.find('#' + tabId).addClass('active');
            
            // Save to localStorage
            this.saveTab(containerId, tabId);
            
            // Trigger custom event
            $(document).trigger('aiautotool:tabChanged', [containerId, tabId]);
        },
        
        /**
         * Handle tab button click
         * @param {Event} e - Click event
         */
        handleTabSwitch: function(e) {
            e.preventDefault();
            
            const $btn = $(this);
            const tabId = $btn.data('tab');
            const $container = $btn.closest('[id^="tab-"]');
            
            if ($container.length && tabId) {
                const containerId = $container.attr('id');
                AiautotoolTabs.switchTab(containerId, tabId);
            }
        }
    };

    /**
     * Utility functions
     */
    window.aiautotoolTabs = {
        /**
         * Programmatically switch to a tab
         * @param {string} containerId - Container ID (e.g., 'tab-api-manager')
         * @param {string} tabId - Tab ID (e.g., 'openai', 'gemini')
         */
        switchTo: function(containerId, tabId) {
            AiautotoolTabs.switchTab(containerId, tabId);
        },
        
        /**
         * Get current active tab for a container
         * @param {string} containerId - Container ID
         * @returns {string|null} - Active tab ID or null
         */
        getActiveTab: function(containerId) {
            const $container = $('#' + containerId);
            const $activeBtn = $container.find('.aiautotool-tab-btn.active');
            return $activeBtn.data('tab') || null;
        },
        
        /**
         * Reload a specific tab's content
         * @param {string} containerId - Container ID
         * @param {string} tabId - Tab ID
         */
        reloadTab: function(containerId, tabId) {
            $(document).trigger('aiautotool:reloadTab', [containerId, tabId]);
        }
    };

    /**
     * Initialize when document is ready
     */
    $(document).ready(function() {
        AiautotoolTabs.init();
    });

    /**
     * Expose to global scope for backward compatibility
     */
    window.AiautotoolTabs = AiautotoolTabs;

})(jQuery);

