/**
 * Frontend JavaScript for HD SofT AI Summary
 *
 * @package HDSofT\AISummary
 */

(function($) {
    'use strict';

    $(document).ready(function() {
        // Initialize summary containers
        initializeSummaryContainers();
        
        // Add fade-in animation to existing summaries
        $('.hdsoft-ai-summary-container, .hdsoft-ai-summary').addClass('hdsoft-ai-summary-fade-in');
        
        // Handle dynamic content loading with MutationObserver
        if ('MutationObserver' in window) {
            var observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (mutation.type === 'childList') {
                        mutation.addedNodes.forEach(function(node) {
                            if (node.nodeType === 1) { // Element node
                                var $node = $(node);
                                if ($node.hasClass('hdsoft-ai-summary-container') || $node.hasClass('hdsoft-ai-summary')) {
                                    initializeSummaryContainer($node);
                                }
                                // Also check child nodes
                                $node.find('.hdsoft-ai-summary-container, .hdsoft-ai-summary').each(function() {
                                    initializeSummaryContainer($(this));
                                });
                            }
                        });
                    }
                });
            });
            observer.observe(document.body, { childList: true, subtree: true });
        }
    });

    /**
     * Initialize all summary containers
     */
    function initializeSummaryContainers() {
        $('.hdsoft-ai-summary-container, .hdsoft-ai-summary').each(function() {
            initializeSummaryContainer($(this));
        });
    }

    /**
     * Initialize a single summary container
     *
     * @param {jQuery} $container Summary container element
     */
    function initializeSummaryContainer($container) {
        // Add accessibility attributes
        if (!$container.attr('role')) {
            $container.attr('role', 'complementary');
        }
        
        if (!$container.attr('aria-label')) {
            $container.attr('aria-label', 'Article summary');
        }
        
        // Add tabindex for keyboard navigation
        if (!$container.attr('tabindex')) {
            $container.attr('tabindex', '0');
        }
        
        // Handle keyboard navigation
        $container.on('keydown', function(e) {
            // Allow Enter and Space to focus the container
            if (e.which === 13 || e.which === 32) {
                e.preventDefault();
                $(this).focus();
            }
        });
        
        // Add smooth scroll behavior for anchor links within summaries
        $container.find('a[href^="#"]').on('click', function(e) {
            var target = $(this.getAttribute('href'));
            if (target.length) {
                e.preventDefault();
                $('html, body').animate({
                    scrollTop: target.offset().top - 100
                }, 500);
            }
        });
        
        // Track summary interactions for analytics (if needed)
        trackSummaryInteraction($container);
    }

    /**
     * Track summary interactions
     *
     * @param {jQuery} $container Summary container element
     */
    function trackSummaryInteraction($container) {
        // Track when summary comes into view
        if ('IntersectionObserver' in window) {
            var observer = new IntersectionObserver(function(entries) {
                entries.forEach(function(entry) {
                    if (entry.isIntersecting) {
                        // Summary is visible
                        triggerEvent('summary_viewed', {
                            post_id: hdsoft_ai_summary_frontend.post_id,
                            summary_type: $container.hasClass('hdsoft-ai-summary-container') ? 'auto' : 'shortcode'
                        });
                        
                        // Stop observing after first view
                        observer.unobserve(entry.target);
                    }
                });
            }, {
                threshold: 0.5 // Trigger when 50% visible
            });
            
            observer.observe($container[0]);
        }
        
        // Track clicks on summary content
        $container.on('click', 'a', function() {
            triggerEvent('summary_link_clicked', {
                post_id: hdsoft_ai_summary_frontend.post_id,
                link_url: $(this).attr('href')
            });
        });
        
        // Track copy events
        $container.on('copy', function() {
            triggerEvent('summary_copied', {
                post_id: hdsoft_ai_summary_frontend.post_id
            });
        });
    }

    /**
     * Trigger custom events for analytics
     *
     * @param {string} eventName Event name
     * @param {Object} data Event data
     */
    function triggerEvent(eventName, data) {
        // Trigger jQuery event
        $(document).trigger('hdsoft_ai_summary_' + eventName, data);
        
        // Send to Google Analytics if available
        if (typeof gtag !== 'undefined') {
            gtag('event', eventName, {
                custom_parameter_1: data.post_id,
                custom_parameter_2: data.summary_type || data.link_url
            });
        }
        
        // Send to Google Analytics (Universal Analytics) if available
        if (typeof ga !== 'undefined') {
            ga('send', 'event', 'AI Summary', eventName, data.post_id);
        }
    }

    /**
     * Add copy to clipboard functionality
     */
    function addCopyFunctionality() {
        // Add copy button to summaries (optional feature)
        $('.hdsoft-ai-summary-container, .hdsoft-ai-summary').each(function() {
            var $container = $(this);
            var $content = $container.find('.hdsoft-ai-summary-content');
            
            if ($content.length && !$container.find('.hdsoft-copy-button').length) {
                var $copyButton = $('<button class="hdsoft-copy-button" title="Copy summary to clipboard">' +
                    '<span class="hdsoft-copy-icon">📋</span>' +
                    '</button>');
                
                $copyButton.on('click', function(e) {
                    e.preventDefault();
                    copyToClipboard($content.text(), $copyButton);
                });
                
                $container.find('.hdsoft-ai-summary-title').append($copyButton);
            }
        });
    }

    /**
     * Copy text to clipboard
     *
     * @param {string} text Text to copy
     * @param {jQuery} $button Copy button element
     */
    function copyToClipboard(text, $button) {
        if (navigator.clipboard && window.isSecureContext) {
            // Use modern clipboard API
            navigator.clipboard.writeText(text).then(function() {
                showCopySuccess($button);
            }).catch(function() {
                fallbackCopyToClipboard(text, $button);
            });
        } else {
            // Fallback for older browsers
            fallbackCopyToClipboard(text, $button);
        }
    }

    /**
     * Fallback copy to clipboard method
     *
     * @param {string} text Text to copy
     * @param {jQuery} $button Copy button element
     */
    function fallbackCopyToClipboard(text, $button) {
        var textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        
        try {
            document.execCommand('copy');
            showCopySuccess($button);
        } catch (err) {
            console.error('Failed to copy text: ', err);
            showCopyError($button);
        }
        
        document.body.removeChild(textArea);
    }

    /**
     * Show copy success feedback
     *
     * @param {jQuery} $button Copy button element
     */
    function showCopySuccess($button) {
        var originalIcon = $button.find('.hdsoft-copy-icon').text();
        $button.find('.hdsoft-copy-icon').text('✓');
        $button.addClass('hdsoft-copy-success');
        
        setTimeout(function() {
            $button.find('.hdsoft-copy-icon').text(originalIcon);
            $button.removeClass('hdsoft-copy-success');
        }, 2000);
        
        triggerEvent('summary_copied', {
            post_id: hdsoft_ai_summary_frontend.post_id
        });
    }

    /**
     * Show copy error feedback
     *
     * @param {jQuery} $button Copy button element
     */
    function showCopyError($button) {
        var originalIcon = $button.find('.hdsoft-copy-icon').text();
        $button.find('.hdsoft-copy-icon').text('✗');
        $button.addClass('hdsoft-copy-error');
        
        setTimeout(function() {
            $button.find('.hdsoft-copy-icon').text(originalIcon);
            $button.removeClass('hdsoft-copy-error');
        }, 2000);
    }

    /**
     * Handle responsive behavior
     */
    function handleResponsiveBehavior() {
        var $summaries = $('.hdsoft-ai-summary-container, .hdsoft-ai-summary');
        
        function adjustSummaryLayout() {
            var windowWidth = $(window).width();
            
            $summaries.each(function() {
                var $summary = $(this);
                
                if (windowWidth <= 480) {
                    $summary.addClass('hdsoft-mobile-layout');
                } else {
                    $summary.removeClass('hdsoft-mobile-layout');
                }
            });
        }
        
        // Initial adjustment
        adjustSummaryLayout();
        
        // Adjust on window resize (debounced)
        var resizeTimer;
        $(window).on('resize', function() {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(adjustSummaryLayout, 250);
        });
    }

    /**
     * Initialize print styles
     */
    function initializePrintStyles() {
        // Add print-specific behavior
        window.addEventListener('beforeprint', function() {
            $('.hdsoft-ai-summary-container, .hdsoft-ai-summary').addClass('hdsoft-printing');
        });
        
        window.addEventListener('afterprint', function() {
            $('.hdsoft-ai-summary-container, .hdsoft-ai-summary').removeClass('hdsoft-printing');
        });
    }

    // Initialize additional features
    handleResponsiveBehavior();
    initializePrintStyles();
    
    // Optionally enable copy functionality (can be controlled via settings)
    if (typeof hdsoft_ai_summary_frontend !== 'undefined' && hdsoft_ai_summary_frontend.enable_copy) {
        addCopyFunctionality();
    }

    // Expose public API for theme developers
    window.HDSofTAISummary = {
        initializeContainer: initializeSummaryContainer,
        copyToClipboard: copyToClipboard,
        triggerEvent: triggerEvent
    };

})(jQuery);
