/**
 * HVAC Help System JavaScript
 * Handles welcome guide interactions, tooltips, and documentation navigation
 */

(function($) {
    'use strict';
    
    let currentCard = 0;
    let totalCards = 0;
    
    $(document).ready(function() {
        initializeWelcomeGuide();
        initializeTooltips();
        initializeDocumentationNavigation();
    });
    
    /**
     * Initialize welcome guide functionality
     */
    function initializeWelcomeGuide() {
        const $modal = $('#hvac-welcome-modal');
        if ($modal.length === 0) return;
        
        totalCards = $('.hvac-welcome-card').length;
        
        // Close button
        $('.hvac-modal-close').on('click', function() {
            closeWelcomeGuide(false);
        });
        
        // Navigation buttons
        $('#hvac-prev-card').on('click', function() {
            navigateCard(-1);
        });
        
        $('#hvac-next-card').on('click', function() {
            navigateCard(1);
        });
        
        // Indicator dots
        $('.hvac-indicator').on('click', function() {
            const targetCard = parseInt($(this).data('card'));
            goToCard(targetCard);
        });
        
        // Get started button
        $('#hvac-get-started').on('click', function() {
            const dontShowAgain = $('#hvac-dont-show-again').is(':checked');
            closeWelcomeGuide(dontShowAgain);
        });
        
        // Keyboard navigation
        $(document).on('keydown', function(e) {
            if ($modal.is(':visible')) {
                switch(e.key) {
                    case 'ArrowLeft':
                        e.preventDefault();
                        navigateCard(-1);
                        break;
                    case 'ArrowRight':
                        e.preventDefault();
                        navigateCard(1);
                        break;
                    case 'Escape':
                        e.preventDefault();
                        closeWelcomeGuide(false);
                        break;
                }
            }
        });
        
        // Click outside to close
        $modal.on('click', function(e) {
            if (e.target === this) {
                closeWelcomeGuide(false);
            }
        });
        
        updateNavigationState();
    }
    
    /**
     * Navigate to previous or next card
     */
    function navigateCard(direction) {
        const newCard = currentCard + direction;
        if (newCard >= 0 && newCard < totalCards) {
            goToCard(newCard);
        }
    }
    
    /**
     * Go to specific card
     */
    function goToCard(cardIndex) {
        if (cardIndex < 0 || cardIndex >= totalCards) return;
        
        // Hide current card
        $('.hvac-welcome-card').removeClass('active').addClass('hidden');
        $('.hvac-indicator').removeClass('active');
        
        // Show target card with animation delay
        setTimeout(function() {
            $('.hvac-welcome-card').eq(cardIndex).removeClass('hidden').addClass('active');
            $('.hvac-indicator').eq(cardIndex).addClass('active');
            currentCard = cardIndex;
            updateNavigationState();
        }, 200);
    }
    
    /**
     * Update navigation button states
     */
    function updateNavigationState() {
        $('#hvac-prev-card').prop('disabled', currentCard === 0);
        $('#hvac-next-card').prop('disabled', currentCard === totalCards - 1);
        
        // Update button text on last card
        if (currentCard === totalCards - 1) {
            $('#hvac-next-card').text('Finish');
        } else {
            $('#hvac-next-card').text('Next');
        }
    }
    
    /**
     * Close welcome guide
     */
    function closeWelcomeGuide(dismissPermanently) {
        const $modal = $('#hvac-welcome-modal');
        
        if (dismissPermanently) {
            // Send AJAX request to set dismissal cookie
            $.ajax({
                url: hvacHelp.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'hvac_dismiss_welcome',
                    nonce: hvacHelp.nonce
                },
                success: function(response) {
                    console.log('Welcome guide dismissed permanently');
                },
                error: function() {
                    console.warn('Failed to save welcome guide dismissal');
                }
            });
        }
        
        // Animate out
        $modal.css('opacity', '0');
        $modal.find('.hvac-modal-content').css({
            'transform': 'scale(0.9) translateY(20px)',
            'opacity': '0'
        });
        
        setTimeout(function() {
            $modal.remove();
        }, 300);
    }
    
    /**
     * Initialize tooltip functionality
     */
    function initializeTooltips() {
        // Enhanced tooltip handling with better positioning
        $('.hvac-tooltip-wrapper').each(function() {
            const $wrapper = $(this);
            let timeoutId;
            
            $wrapper.on('mouseenter', function() {
                timeoutId = setTimeout(function() {
                    // Add a class to show tooltip
                    $wrapper.addClass('hvac-tooltip-visible');
                }, 500); // 500ms delay
            });
            
            $wrapper.on('mouseleave', function() {
                clearTimeout(timeoutId);
                $wrapper.removeClass('hvac-tooltip-visible');
            });
        });
        
        // Add tooltip classes for enhanced styling
        $('.hvac-tooltip-wrapper[data-tooltip]').addClass('hvac-has-tooltip');
    }
    
    /**
     * Initialize documentation page navigation
     */
    function initializeDocumentationNavigation() {
        // Smooth scrolling for documentation links
        $('.hvac-doc-link').on('click', function(e) {
            e.preventDefault();
            const targetId = $(this).attr('href');
            const $target = $(targetId);
            
            if ($target.length) {
                $('html, body').animate({
                    scrollTop: $target.offset().top - 80
                }, 600);
                
                // Update active state
                $('.hvac-doc-link').removeClass('active');
                $(this).addClass('active');
            }
        });
        
        // Highlight current section on scroll
        $(window).on('scroll', function() {
            const scrollTop = $(window).scrollTop();
            const windowHeight = $(window).height();
            
            $('.hvac-doc-section').each(function() {
                const $section = $(this);
                const sectionTop = $section.offset().top;
                const sectionBottom = sectionTop + $section.outerHeight();
                
                if (scrollTop + 120 >= sectionTop && scrollTop + 120 < sectionBottom) {
                    const sectionId = $section.attr('id');
                    $('.hvac-doc-link').removeClass('active');
                    $('.hvac-doc-link[href="#' + sectionId + '"]').addClass('active');
                }
            });
        });
        
        // Add fade-in animation for FAQ items
        $('.hvac-faq-item').each(function(index) {
            $(this).css({
                'opacity': '0',
                'transform': 'translateY(20px)'
            });
            
            $(this).delay(index * 100).animate({
                'opacity': '1'
            }, 400).css('transform', 'translateY(0)');
        });
        
        // Collapsible FAQ items (optional enhancement)
        $('.hvac-faq-item h3').on('click', function() {
            const $content = $(this).next('p');
            const $item = $(this).parent();
            
            if ($item.hasClass('hvac-faq-collapsed')) {
                $content.slideDown(300);
                $item.removeClass('hvac-faq-collapsed');
            } else {
                $content.slideUp(300);
                $item.addClass('hvac-faq-collapsed');
            }
        }).css('cursor', 'pointer').attr('title', 'Click to expand/collapse');
    }
    
    /**
     * Add help button to navigation areas
     */
    function addHelpButtons() {
        // Add help button to main navigation if it doesn't exist
        if ($('.hvac-help-button').length === 0) {
            const helpButton = $('<a href="/hvac-documentation" class="hvac-help-button hvac-tooltip-wrapper" data-tooltip="View documentation and help guides" data-position="bottom"><i class="fas fa-question-circle"></i> Help</a>');
            
            // Try to add to existing navigation
            if ($('.hvac-dashboard-nav').length) {
                $('.hvac-dashboard-nav').append(helpButton);
            } else if ($('.hvac-nav-buttons').length) {
                $('.hvac-nav-buttons').append(helpButton);
            }
        }
    }
    
    /**
     * Initialize contextual help
     */
    function initializeContextualHelp() {
        // Add help icon to page titles
        const pageSpecificHelp = {
            'hvac-dashboard': 'Your central hub for managing events, tracking revenue, and viewing performance metrics.',
            'trainer-profile': 'Update your professional information, credentials, and training specialties.',
            'event-summary': 'View detailed information about your event including attendees and sales data.',
            'certificate-reports': 'Generate and manage professional certificates for your training attendees.',
            'email-attendees': 'Communicate with your event attendees using our built-in email system.'
        };
        
        const currentPage = $('body').attr('class').match(/page-id-\d+|page-[\w-]+/);
        if (currentPage) {
            const pageName = currentPage[0].replace('page-', '').replace('page-id-', '');
            
            Object.keys(pageSpecificHelp).forEach(function(page) {
                if (pageName.includes(page) || $('body').hasClass('page-' + page)) {
                    const helpText = pageSpecificHelp[page];
                    const $pageTitle = $('h1').first();
                    
                    if ($pageTitle.length && !$pageTitle.find('.hvac-page-help').length) {
                        $pageTitle.append(' <span class="hvac-page-help hvac-tooltip-wrapper" data-tooltip="' + helpText + '" data-position="right"><i class="fas fa-info-circle"></i></span>');
                    }
                }
            });
        }
    }
    
    // Initialize additional features
    $(document).ready(function() {
        addHelpButtons();
        initializeContextualHelp();
    });
    
    // Public API for other scripts
    window.HVACHelp = {
        addTooltip: function(element, text, position) {
            $(element).addClass('hvac-tooltip-wrapper')
                     .attr('data-tooltip', text)
                     .attr('data-position', position || 'top');
        },
        
        showWelcomeGuide: function() {
            if ($('#hvac-welcome-modal').length === 0) {
                location.reload(); // Reload to show guide
            }
        }
    };
    
})(jQuery);