/**
 * AYSA Plugin - Tabbed Settings Interface JavaScript
 * Handles tab switching functionality and state management
 */

(function($) {
    'use strict';

    // Tab Management Class
    class AysaTabManager {
        constructor() {
            this.activeTab = 'credit-usage-tab';
            this.tabHistory = [];
            this.init();
        }

        init() {
            this.bindEvents();
            this.loadActiveTab();
            this.handleUrlHash();
        }

        bindEvents() {
            // Tab button click handler
            $(document).on('click', '.aysa-tab-button', (e) => {
                e.preventDefault();
                const tabId = $(e.currentTarget).data('tab');
                this.switchTab(tabId);
            });

            // Handle browser back/forward
            $(window).on('hashchange', () => {
                this.handleUrlHash();
            });

            // Keyboard navigation
            $(document).on('keydown', '.aysa-tab-button', (e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    $(e.currentTarget).click();
                }
            });
        }

        switchTab(tabId) {
            if (!tabId || tabId === this.activeTab) {
                return;
            }

            // Add to history
            if (this.activeTab) {
                this.tabHistory.push(this.activeTab);
            }

            // Hide all tab contents
            $('.aysa-tab-content').removeClass('active').hide();
            
            // Remove active class from all buttons
            $('.aysa-tab-button').removeClass('active');

            // Show selected tab content
            const $targetTab = $('#' + tabId);
            const $targetButton = $(`.aysa-tab-button[data-tab="${tabId}"]`);

            if ($targetTab.length && $targetButton.length) {
                $targetTab.addClass('active').fadeIn(300);
                $targetButton.addClass('active');
                
                this.activeTab = tabId;
                
                // Update URL hash
                this.updateUrlHash(tabId);
                
                // Save to localStorage
                this.saveActiveTab(tabId);
                
                // Trigger custom event
                $(document).trigger('aysa:tab:switched', [tabId, this.getTabName(tabId)]);
                
                // Handle tab-specific initialization
                this.initializeTabContent(tabId);
            }
        }

        getTabName(tabId) {
            const tabNames = {
                'credit-usage-tab': 'Credit Usage',
                'api-settings-tab': 'API Settings',
                'general-settings-tab': 'General Settings',
                'automation-settings-tab': 'Automation Settings',
                'advanced-settings-tab': 'Advanced Settings'
            };
            return tabNames[tabId] || 'Unknown Tab';
        }

        initializeTabContent(tabId) {
            switch(tabId) {
                case 'credit-usage-tab':
                    // Refresh credit data if needed
                    if (typeof window.refreshCreditData === 'function') {
                        window.refreshCreditData();
                    }
                    break;
                case 'api-settings-tab':
                    // Initialize API settings if needed
                    break;
                case 'automation-settings-tab':
                    // Initialize automation settings if needed
                    break;
            }
        }

        loadActiveTab() {
            // Try to load from URL hash first
            const hashTab = this.getTabFromHash();
            if (hashTab) {
                this.switchTab(hashTab);
                return;
            }

            // Try to load from localStorage
            const savedTab = localStorage.getItem('aysa_active_tab');
            if (savedTab && $('#' + savedTab).length) {
                this.switchTab(savedTab);
                return;
            }

            // Default to first tab (credit usage)
            this.switchTab('credit-usage-tab');
        }

        saveActiveTab(tabId) {
            try {
                localStorage.setItem('aysa_active_tab', tabId);
            } catch (e) {
                console.warn('Could not save active tab to localStorage:', e);
            }
        }

        updateUrlHash(tabId) {
            const hash = '#tab=' + tabId.replace('-tab', '');
            if (window.location.hash !== hash) {
                history.replaceState(null, null, hash);
            }
        }

        handleUrlHash() {
            const tabId = this.getTabFromHash();
            if (tabId && tabId !== this.activeTab) {
                this.switchTab(tabId);
            }
        }

        getTabFromHash() {
            const hash = window.location.hash;
            const match = hash.match(/^#tab=(.+)$/);
            if (match) {
                const tabName = match[1];
                return tabName + '-tab';
            }
            return null;
        }

        goToPreviousTab() {
            if (this.tabHistory.length > 0) {
                const previousTab = this.tabHistory.pop();
                this.switchTab(previousTab);
            }
        }

        // Public API methods
        getCurrentTab() {
            return this.activeTab;
        }

        isTabActive(tabId) {
            return this.activeTab === tabId;
        }

        getAvailableTabs() {
            return $('.aysa-tab-button').map(function() {
                return $(this).data('tab');
            }).get();
        }
    }

    // Initialize when document is ready
    $(document).ready(function() {
        // Only initialize if we're on the AYSA settings page
        if ($('.aysa-tab-navigation').length > 0) {
            window.aysaTabManager = new AysaTabManager();
            
            // Debug logging
            if (window.aysaDebug) {
                console.log('AYSA Tab Manager initialized');
                
                $(document).on('aysa:tab:switched', function(e, tabId, tabName) {
                    console.log('Tab switched to:', tabName, '(' + tabId + ')');
                });
            }
        }
    });

    // Expose utility functions globally
    window.aysaTabUtils = {
        switchToTab: function(tabId) {
            if (window.aysaTabManager) {
                window.aysaTabManager.switchTab(tabId);
            }
        },
        
        getCurrentTab: function() {
            return window.aysaTabManager ? window.aysaTabManager.getCurrentTab() : null;
        },
        
        goToPreviousTab: function() {
            if (window.aysaTabManager) {
                window.aysaTabManager.goToPreviousTab();
            }
        }
    };

})(jQuery);