jQuery(document).ready(function($) {
    
    // FAQ Toggle functionality
    $('.pc-faq-toggle').on('click', function(e) {
        e.preventDefault();
        
        var $button = $(this);
        var $faqItem = $button.closest('.pc-faq-item');
        var $answer = $faqItem.find('.pc-faq-answer');
        var isExpanded = $button.attr('aria-expanded') === 'true';
        
        // Close all other FAQs (optional accordion behavior)
        $('.pc-faq-item').each(function() {
            if ($(this)[0] !== $faqItem[0]) {
                $(this).removeClass('is-open');
                $(this).find('.pc-faq-answer').slideUp(300);
                $(this).find('.pc-faq-toggle').attr('aria-expanded', 'false');
            }
        });
        
        // Toggle current FAQ
        if (isExpanded) {
            $faqItem.removeClass('is-open');
            $answer.slideUp(300);
            $button.attr('aria-expanded', 'false');
        } else {
            $faqItem.addClass('is-open');
            $answer.slideDown(300);
            $button.attr('aria-expanded', 'true');
            
            // Smooth scroll to the FAQ
            setTimeout(function() {
                $('html, body').animate({
                    scrollTop: $faqItem.offset().top - 20
                }, 300);
            }, 100);
        }
    });
    
    // Keyboard navigation
    $('.pc-faq-toggle').on('keydown', function(e) {
        var $button = $(this);
        var $faqItem = $button.closest('.pc-faq-item');
        var $allItems = $('.pc-faq-item');
        var currentIndex = $allItems.index($faqItem);
        
        switch (e.keyCode) {
            case 38: // Up arrow
                e.preventDefault();
                if (currentIndex > 0) {
                    $allItems.eq(currentIndex - 1).find('.pc-faq-toggle').focus();
                }
                break;
                
            case 40: // Down arrow
                e.preventDefault();
                if (currentIndex < $allItems.length - 1) {
                    $allItems.eq(currentIndex + 1).find('.pc-faq-toggle').focus();
                }
                break;
                
            case 36: // Home
                e.preventDefault();
                $allItems.first().find('.pc-faq-toggle').focus();
                break;
                
            case 35: // End
                e.preventDefault();
                $allItems.last().find('.pc-faq-toggle').focus();
                break;
        }
    });
    
    // Search functionality (if search box is added)
    function initSearch() {
        var $searchBox = $('#pc-faq-search');
        if ($searchBox.length === 0) return;
        
        $searchBox.on('input', function() {
            var searchTerm = $(this).val().toLowerCase();
            var $faqs = $('.pc-faq-item');
            var visibleCount = 0;
            
            $faqs.each(function() {
                var $faqItem = $(this);
                var question = $faqItem.find('.pc-faq-question-text').text().toLowerCase();
                var answer = $faqItem.find('.pc-faq-answer-content').text().toLowerCase();
                
                if (question.includes(searchTerm) || answer.includes(searchTerm)) {
                    $faqItem.show();
                    visibleCount++;
                } else {
                    $faqItem.hide();
                }
            });
            
            // Show no results message
            var $noResults = $('.pc-faq-no-results');
            if (visibleCount === 0 && searchTerm !== '') {
                if ($noResults.length === 0) {
                    $noResults = $('<div class="pc-faq-no-results" style="text-align: center; padding: 40px 20px; color: #666; font-style: italic;"></div>');
                    $('.pc-faq-items').append($noResults);
                }
                $noResults.text('No FAQs found matching "' + searchTerm + '"');
            } else {
                $noResults.remove();
            }
            
            // Update count
            var $count = $('.pc-faq-count');
            if ($count.length > 0) {
                if (searchTerm === '') {
                    $count.text($faqs.length + ' FAQs available');
                } else {
                    $count.text(visibleCount + ' of ' + $faqs.length + ' FAQs matching "' + searchTerm + '"');
                }
            }
        });
    }
    
    // Initialize search if present
    initSearch();
    
    // Expand/Collapse All functionality
    function initExpandCollapseAll() {
        var $expandAll = $('#pc-faq-expand-all');
        var $collapseAll = $('#pc-faq-collapse-all');
        
        if ($expandAll.length === 0 && $collapseAll.length === 0) return;
        
        $expandAll.on('click', function() {
            $('.pc-faq-item').addClass('is-open');
            $('.pc-faq-answer').slideDown(300);
            $('.pc-faq-toggle').attr('aria-expanded', 'true');
        });
        
        $collapseAll.on('click', function() {
            $('.pc-faq-item').removeClass('is-open');
            $('.pc-faq-answer').slideUp(300);
            $('.pc-faq-toggle').attr('aria-expanded', 'false');
        });
    }
    
    initExpandCollapseAll();
    
    // Print functionality
    function initPrintButton() {
        var $printButton = $('#pc-faq-print');
        if ($printButton.length === 0) return;
        
        $printButton.on('click', function(e) {
            e.preventDefault();
            window.print();
        });
    }
    
    initPrintButton();
    
    // URL hash functionality
    function initHashNavigation() {
        if (window.location.hash) {
            var hash = window.location.hash.substring(1);
            var $targetFaq = $('#pc-faq-' + hash);
            
            if ($targetFaq.length > 0) {
                // Close all FAQs first
                $('.pc-faq-item').removeClass('is-open');
                $('.pc-faq-answer').slideUp(300);
                $('.pc-faq-toggle').attr('aria-expanded', 'false');
                
                // Open the target FAQ
                setTimeout(function() {
                    $targetFaq.find('.pc-faq-toggle').trigger('click');
                }, 500);
            }
        }
    }
    
    initHashNavigation();
    
    // Update hash when FAQ is opened
    $('.pc-faq-toggle').on('click', function() {
        var $faqItem = $(this).closest('.pc-faq-item');
        var faqId = $faqItem.attr('id');
        
        if (faqId && $faqItem.hasClass('is-open')) {
            history.pushState(null, null, '#' + faqId.replace('pc-faq-', ''));
        } else {
            if (window.location.hash) {
                history.pushState(null, null, window.location.pathname);
            }
        }
    });
    
    // Analytics tracking (if available)
    function trackFAQInteraction(action, faqId) {
        if (typeof gtag !== 'undefined') {
            gtag('event', 'faq_' + action, {
                'faq_id': faqId
            });
        } else if (typeof ga !== 'undefined') {
            ga('send', 'event', 'FAQ', action, faqId);
        }
    }
    
    // Track FAQ opens
    $('.pc-faq-toggle').on('click', function() {
        var $faqItem = $(this).closest('.pc-faq-item');
        var faqId = $faqItem.data('faq-id') || $faqItem.attr('id');
        var question = $faqItem.find('.pc-faq-question-text').text();
        
        trackFAQInteraction('open', faqId);
        trackFAQInteraction('open_question', question);
    });
    
    // Performance optimization: Lazy load images in answers
    function lazyLoadImages() {
        if ('IntersectionObserver' in window) {
            var imageObserver = new IntersectionObserver(function(entries, observer) {
                entries.forEach(function(entry) {
                    if (entry.isIntersecting) {
                        var img = entry.target;
                        if (img.dataset.src) {
                            img.src = img.dataset.src;
                            img.removeAttribute('data-src');
                            observer.unobserve(img);
                        }
                    }
                });
            });
            
            $('.pc-faq-answer-content img[data-src]').each(function() {
                imageObserver.observe(this);
            });
        }
    }
    
    lazyLoadImages();
    
    // Smooth scroll behavior for anchor links within answers
    $('.pc-faq-answer-content a[href^="#"]').on('click', function(e) {
        var target = $(this.getAttribute('href'));
        if (target.length) {
            e.preventDefault();
            $('html, body').animate({
                scrollTop: target.offset().top - 20
            }, 300);
        }
    });
});