/**
 * Super Agency Theme - Admin JavaScript
 * Handles interactive functionality for the theme settings page
 */

(function($) {
    'use strict';

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

    const SuperAgencyAdmin = {
        
        // Cache jQuery objects
        $document: $(document),
        $window: $(window),
        $body: $('body'),
        
        // Plugin data cache
        pluginsData: [],
        
        /**
         * Initialize all functionality
         */
        init: function() {
            this.bindEvents();
            this.initTabs();
        },
        
        /**
         * Bind all event listeners
         */
        bindEvents: function() {
            // Tab switching
            this.$document.on('click', '.nav-tab', this.handleTabSwitch);
            
            // Plugin installation
            this.$document.on('click', '.install-button', this.handlePluginInstall);
            
            // Card hover effects
            this.$document.on('mouseenter', '.settings-card', this.handleCardHover);
            this.$document.on('mouseleave', '.settings-card', this.handleCardLeave);
            
            // Keyboard navigation
            this.$document.on('keydown', this.handleKeyboardNav);
        },
        
        /**
         * Initialize tab functionality
         */
        initTabs: function() {
            // Prefer query-string tab (used after form submissions) over URL hash
            const urlParams = new URLSearchParams(window.location.search);
            const queryTab  = urlParams.get('tab');
            const urlHash   = window.location.hash;

            if (queryTab && $('#' + queryTab).length) {
                this.switchTab(queryTab);
            } else if (urlHash && $(urlHash).length) {
                this.switchTab(urlHash.substring(1));
            }
        },
        
        /**
         * Handle tab switching
         */
        handleTabSwitch: function(e) {
            e.preventDefault();
            const tabName = $(this).data('tab');
            SuperAgencyAdmin.switchTab(tabName);
            
            // Update URL without page reload
            if (history.pushState) {
                history.pushState(null, null, '#' + tabName);
            }
        },
        
        /**
         * Switch to specific tab
         */
        switchTab: function(tabName) {
            // Hide all tab panels
            $('.tab-panel').removeClass('active');
            
            // Remove active class from all tabs
            $('.nav-tab').removeClass('nav-tab-active');
            
            // Show selected tab panel
            $('#' + tabName).addClass('active');
            
            // Add active class to clicked tab
            $('[data-tab="' + tabName + '"]').addClass('nav-tab-active');
            
            // Load plugins if plugins tab is selected
            if (tabName === 'plugins') {
                this.loadPlugins();
            }
            
            // Trigger custom event
            this.$document.trigger('superAgencyTabSwitched', [tabName]);
        },
        
        /**
         * Load plugins - now using predefined data
         */
        loadPlugins: function() {
            const $container = $('#plugins-container');
            
            // Show loading if not already loaded
            if (this.pluginsData.length === 0) {
                $container.html(this.getLoadingHTML());
                
                $.ajax({
                    url: superAgencyAdmin.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'super_agency_get_plugins',
                        nonce: superAgencyAdmin.nonce
                    },
                    success: (response) => {
                        if (response.success) {
                            this.pluginsData = response.data;
                            this.renderPlugins();
                        } else {
                            this.showError(response.data.message || 'Failed to load plugins');
                        }
                    },
                    error: () => {
                        this.showError('Network error occurred while loading plugins');
                    }
                });
            } else {
                this.renderPlugins();
            }
        },
        
        /**
         * Render plugins grid
         */
        renderPlugins: function() {
            const $container = $('#plugins-container');
            
            if (this.pluginsData.length === 0) {
                $container.html(this.getNoPluginsHTML());
                return;
            }
            
            let html = '<div class="cards-grid">';
            
            this.pluginsData.forEach((plugin) => {
                html += this.getPluginCardHTML(plugin);
            });
            
            html += '</div>';
            $container.html(html);
            
            // Add animation
            setTimeout(() => {
                $container.find('.plugin-card').addClass('animate-in');
            }, 100);
        },
        
        /**
         * Get plugin card HTML - Clean design without icons
         */
        getPluginCardHTML: function(plugin) {
            const isInstalled = this.isPluginInstalled(plugin.slug);
            
            return `
                <div class="plugin-card" data-slug="${plugin.slug}">
                    <div class="plugin-header">
                        <div class="plugin-info">
                            <h4>${plugin.name}</h4>
                        </div>
                    </div>
                    <div class="plugin-description">
                        ${plugin.short_description || 'No description available.'}
                    </div>
                    <div class="plugin-actions">
                        ${isInstalled ? 
                            '<button class="install-button installed" disabled>Installed ✓</button>' :
                            `<button class="install-button" data-slug="${plugin.slug}">Install Now</button>`
                        }
                        <a href="${plugin.download_link || 'https://wordpress.org/plugins/' + plugin.slug + '/'}" target="_blank" class="view-details">View Details</a>
                    </div>
                </div>
            `;
        },
        
        /**
         * Check if plugin is installed - Now uses real data from PHP
         */
        isPluginInstalled: function(slug) {
            // Check against the installed plugins list passed from PHP
            return superAgencyAdmin.installed_plugins && 
                   superAgencyAdmin.installed_plugins.indexOf(slug) !== -1;
        },
        
        /**
         * Handle plugin installation
         */
        handlePluginInstall: function(e) {
            e.preventDefault();
            
            const $button = $(this);
            const pluginSlug = $button.data('slug');
            const originalText = $button.text();
            
            // Prevent double-clicking
            if ($button.hasClass('installing') || $button.hasClass('installed')) {
                return;
            }
            
            // Update button state
            $button.text(superAgencyAdmin.strings.installing)
                   .addClass('installing')
                   .prop('disabled', true);
            
            $.ajax({
                url: superAgencyAdmin.ajaxurl,
                type: 'POST',
                data: {
                    action: 'super_agency_install_plugin',
                    plugin_slug: pluginSlug,
                    nonce: superAgencyAdmin.nonce
                },
                timeout: 60000, // 60 second timeout for plugin installation
                success: (response) => {
                    if (response.success) {
                        $button.text(superAgencyAdmin.strings.installed)
                               .removeClass('installing')
                               .addClass('installed');
                        
                        // Add to installed plugins list
                        if (superAgencyAdmin.installed_plugins.indexOf(pluginSlug) === -1) {
                            superAgencyAdmin.installed_plugins.push(pluginSlug);
                        }
                        
                        SuperAgencyAdmin.showNotice(response.data.message, 'success');
                    } else {
                        $button.text(originalText)
                               .removeClass('installing')
                               .prop('disabled', false);
                        
                        SuperAgencyAdmin.showNotice(response.data.message || 'Installation failed', 'error');
                    }
                },
                error: (xhr, status, error) => {
                    $button.text(originalText)
                           .removeClass('installing')
                           .prop('disabled', false);
                    
                    let errorMessage = 'Network error occurred during installation';
                    if (status === 'timeout') {
                        errorMessage = 'Installation timed out. Please try again.';
                    }
                    
                    SuperAgencyAdmin.showNotice(errorMessage, 'error');
                }
            });
        },
        
        /**
         * Handle card hover effects
         */
        handleCardHover: function() {
            $(this).find('.card-icon').addClass('hover-effect');
        },
        
        /**
         * Handle card leave effects
         */
        handleCardLeave: function() {
            $(this).find('.card-icon').removeClass('hover-effect');
        },
        
        /**
         * Handle keyboard navigation
         */
        handleKeyboardNav: function(e) {
            // Tab navigation with arrow keys
            if (e.target.classList.contains('nav-tab')) {
                const $tabs = $('.nav-tab');
                const currentIndex = $tabs.index(e.target);
                
                if (e.keyCode === 37) { // Left arrow
                    e.preventDefault();
                    const prevIndex = currentIndex > 0 ? currentIndex - 1 : $tabs.length - 1;
                    $tabs.eq(prevIndex).focus().click();
                } else if (e.keyCode === 39) { // Right arrow
                    e.preventDefault();
                    const nextIndex = currentIndex < $tabs.length - 1 ? currentIndex + 1 : 0;
                    $tabs.eq(nextIndex).focus().click();
                }
            }
        },
        
        /**
         * Show success/error notice
         */
        showNotice: function(message, type = 'success') {
            const iconClass = type === 'success' ? 'dashicons-yes' : 'dashicons-warning';
            const noticeHTML = `
                <div class="super-agency-notice ${type}">
                    <span class="dashicons ${iconClass}"></span>
                    <span>${message}</span>
                    <button type="button" class="notice-dismiss-custom" aria-label="Dismiss notice">
                        <span class="dashicons dashicons-dismiss"></span>
                    </button>
                </div>
            `;
            
            // Remove existing notices
            $('.super-agency-notice').remove();
            
            // Add new notice
            $('.tab-content').prepend(noticeHTML);
            
            // Handle manual dismiss
            $('.notice-dismiss-custom').on('click', function() {
                $(this).closest('.super-agency-notice').fadeOut(300, function() {
                    $(this).remove();
                });
            });
            
            // Auto-remove after 5 seconds
            setTimeout(() => {
                $('.super-agency-notice').fadeOut(300, function() {
                    $(this).remove();
                });
            }, 5000);
        },
        
        /**
         * Show error message
         */
        showError: function(message) {
            $('#plugins-container').html(`
                <div class="no-plugins">
                    <span class="dashicons dashicons-warning"></span>
                    <h3>Error Loading Plugins</h3>
                    <p>${message}</p>
                    <button class="card-button" onclick="SuperAgencyAdmin.loadPlugins()">Try Again</button>
                </div>
            `);
        },
        
        /**
         * Get loading HTML
         */
        getLoadingHTML: function() {
            return `
                <div class="loading">
                    <div class="spinner"></div>
                    <p>${superAgencyAdmin.strings.loading}</p>
                </div>
            `;
        },
        
        /**
         * Get no plugins HTML
         */
        getNoPluginsHTML: function() {
            return `
                <div class="no-plugins">
                    <span class="dashicons dashicons-admin-plugins"></span>
                    <h3>No Plugins Found</h3>
                    <p>No plugins available at this time.</p>
                </div>
            `;
        }
    };
    
    // Expose to global scope
    window.SuperAgencyAdmin = SuperAgencyAdmin;
    
})(jQuery);

/**
 * Vanilla JavaScript fallback for non-jQuery environments
 */
if (typeof jQuery === 'undefined') {
    console.warn('Super Agency Admin: jQuery not found, some features may not work properly.');
    
    // Basic tab switching fallback
    document.addEventListener('DOMContentLoaded', function() {
        const tabs = document.querySelectorAll('.nav-tab');
        const panels = document.querySelectorAll('.tab-panel');
        
        tabs.forEach(tab => {
            tab.addEventListener('click', function(e) {
                e.preventDefault();
                
                // Remove active classes
                tabs.forEach(t => t.classList.remove('nav-tab-active'));
                panels.forEach(p => p.classList.remove('active'));
                
                // Add active classes
                this.classList.add('nav-tab-active');
                const tabName = this.getAttribute('data-tab');
                const panel = document.getElementById(tabName);
                if (panel) {
                    panel.classList.add('active');
                }
            });
        });
    });
}