/**
 * JavaScript for handling PRO feature tooltips in the Text to Speech plugin
 *
 * @package    Mementor_TTS
 * @subpackage Mementor_TTS/admin/js
 */

// Define the tooltip functionality in a way that can be called from other scripts
var MementorTTSTooltips = (function($) {
    // Setup tooltip for a specific button
    function setupTooltipForButton(button) {
        const tooltipId = button.data('tooltip-id');
        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Processing button with tooltip ID:', tooltipId);
        
        // Check if the tooltip content exists
        const tooltipContent = $('#' + tooltipId);
        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Tooltip content element exists:', tooltipContent.length > 0);
        
        if (tooltipContent.length) {
            if (window.mementorTTSDebug) window.mementorTTSDebug.log('Found tooltip content for ID:', tooltipId);
            
            // IMPORTANT: Remove the title attribute to prevent default browser tooltip
            if (button.attr('title')) {
                // Store the original title in a data attribute in case we need it later
                button.data('original-title', button.attr('title'));
                button.removeAttr('title');
                if (window.mementorTTSDebug) window.mementorTTSDebug.log('Removed title attribute from button');
            }
            
            // Create tooltip element
            const tooltipElement = $('<div class="mementor-tts-tooltip" id="tooltip-for-' + tooltipId + '"></div>')
                .html(tooltipContent.html());
            
            // Add tooltip to the DOM
            $('body').append(tooltipElement);
            
            // Position the tooltip relative to the button
            const buttonOffset = button.offset();
            const buttonWidth = button.outerWidth();
            const buttonHeight = button.outerHeight();
            
            // Initially show the tooltip to get its dimensions
            tooltipElement.css('visibility', 'hidden').show();
            const tooltipWidth = tooltipElement.outerWidth() || 420;
            tooltipElement.hide().css('visibility', 'visible');
            
            // Calculate position to center the tooltip under the button
            const leftPosition = buttonOffset.left + (buttonWidth - tooltipWidth) / 2;
            const topPosition = buttonOffset.top + buttonHeight + 5; // 5px gap
            
            // Apply positioning
            tooltipElement.css({
                'position': 'absolute',
                'top': topPosition + 'px',
                'left': leftPosition + 'px',
                'z-index': 99999
            });
            
            // Remove any existing event handlers to avoid duplicates
            button.off('mouseenter mouseleave click');
            
            // Store reference to tooltip in button's data for easy access
            button.data('tooltipElement', tooltipElement);
            
            // Use direct event binding instead of hover() method for better compatibility with disabled buttons
            button.on('mouseenter', function(e) {
                // Removed e.stopPropagation() to prevent interference with other plugins
                if (window.mementorTTSDebug) window.mementorTTSDebug.log('Mouseenter event triggered for button:', $(this).data('tooltip-id'));
                const tooltipElem = $(this).data('tooltipElement');
                if (tooltipElem) {
                    if (window.mementorTTSDebug) window.mementorTTSDebug.log('Showing tooltip element');
                    // Reposition tooltip in case page has changed
                    const btnOffset = $(this).offset();
                    const btnWidth = $(this).outerWidth();
                    const btnHeight = $(this).outerHeight();
                    const tipWidth = tooltipElem.outerWidth() || 420;
                    
                    tooltipElem.css({
                        'top': (btnOffset.top + btnHeight + 5) + 'px',
                        'left': (btnOffset.left + (btnWidth - tipWidth) / 2) + 'px'
                    }).fadeIn(200);
                } else {
                    if (window.mementorTTSDebug) window.mementorTTSDebug.log('No tooltip element found in button data');
                }
            });
            
            // Track if mouse is over button or tooltip
            let mouseOverButton = false;
            let mouseOverTooltip = false;
            
            button.on('mouseleave', function(e) {
                // Removed e.stopPropagation() to prevent interference with other plugins
                if (window.mementorTTSDebug) window.mementorTTSDebug.log('Mouse left button');
                mouseOverButton = false;
                const tooltipElem = $(this).data('tooltipElement');
                if (tooltipElem) {
                    // Only hide if mouse is not over the tooltip
                    setTimeout(function() {
                        if (!mouseOverButton && !mouseOverTooltip) {
                            if (window.mementorTTSDebug) window.mementorTTSDebug.log('Hiding tooltip from button leave - neither over button nor tooltip');
                            tooltipElem.fadeOut(200);
                        }
                    }, 300); // Increased delay to allow moving to tooltip
                }
            });
            
            button.on('mouseenter', function(e) {
                mouseOverButton = true;
            });
            
            // Keep tooltip visible when hovering over it
            tooltipElement.on('mouseenter', function() {
                if (window.mementorTTSDebug) window.mementorTTSDebug.log('Mouse entered tooltip');
                mouseOverTooltip = true;
                $(this).stop(true, true).show();
            });
            
            tooltipElement.on('mouseleave', function() {
                if (window.mementorTTSDebug) window.mementorTTSDebug.log('Mouse left tooltip');
                mouseOverTooltip = false;
                const self = $(this);
                // Only hide if mouse is not over the button
                setTimeout(function() {
                    if (!mouseOverButton && !mouseOverTooltip) {
                        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Hiding tooltip - neither over button nor tooltip');
                        self.fadeOut(200);
                    }
                }, 300); // Increased delay to make it easier to move between button and tooltip
            });
            
            button.on('click', function(e) {
                // Only prevent default if this is actually a tooltip button
                if ($(this).hasClass('mementor-tts-pro-feature')) {
                    e.preventDefault();
                    // Removed e.stopPropagation() to prevent interference with other plugins
                    const tooltipElem = $(this).data('tooltipElement');
                    if (tooltipElem) {
                        tooltipElem.fadeToggle(200);
                    }
                }
            });
            
            // Hide tooltip initially
            tooltipElement.hide();
        } else {
            if (window.mementorTTSDebug) window.mementorTTSDebug.log('No tooltip content found for ID:', tooltipId);
        }
    }
    
    // Main initialization function that will be exposed
    function initializeProFeatureTooltips() {
        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Initializing PRO feature tooltips');
        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Looking for buttons with selector: .mementor-tts-pro-feature[data-tooltip-id]');
        
        // First, remove all existing tooltips to avoid duplicates
        $('.mementor-tts-tooltip').remove();
        
        // Target all PRO feature buttons with data-tooltip-id attribute
        var buttons = $('.mementor-tts-pro-feature[data-tooltip-id]');
        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Found ' + buttons.length + ' buttons to process');
        
        buttons.each(function() {
            setupTooltipForButton($(this));
        });
        
        // Enable pointer events on disabled buttons to allow tooltip triggers
        $('.mementor-tts-pro-feature[disabled]').css('pointer-events', 'auto');
        
        // Also ensure the specific SSML buttons have pointer events
        $('.mementor-tts-ssml-btn.mementor-tts-pro-feature').css('pointer-events', 'auto');
    }
    
    // Setup document click handler to close tooltips when clicking outside
    function setupDocumentClickHandler() {
        // Use namespaced event to prevent conflicts
        $(document).on('click.mementorTTS', function(e) {
            // Only handle our tooltips, not interfere with other plugins
            if (!$(e.target).closest('.mementor-tts-pro-feature, .mementor-tts-tooltip').length) {
                $('.mementor-tts-tooltip').fadeOut(200);
            }
        });
    }
    
    // Initialize tooltips and setup handlers
    function init() {
        // Check if tooltips are disabled globally or compatibility mode is active
        if (window.mementorTTSTooltip && window.mementorTTSTooltip.disabled) {
            if (window.mementorTTSDebug) window.mementorTTSDebug.log('Tooltips are disabled - skipping initialization');
            return;
        }
        
        // Check if compatibility mode is active
        if (window.mementorTTSCompatibilityMode || (window.mementorTTS && window.mementorTTS.compatibilityMode)) {
            if (window.mementorTTSDebug) window.mementorTTSDebug.log('Compatibility mode active - skipping tooltip initialization');
            return;
        }
        
        initializeProFeatureTooltips();
        setupDocumentClickHandler();
        
        // Also initialize tooltips after any AJAX content is loaded
        $(document).ajaxComplete(function(event, xhr, settings) {
            // Don't re-initialize if it's a mementor TTS AJAX call
            if (settings && settings.data && 
                (settings.data.includes('mementor_tts') || 
                 settings.data.includes('action=mementor'))) {
                if (window.mementorTTSDebug) window.mementorTTSDebug.log('MementorTTSTooltips: Skipping re-init for TTS AJAX call');
                return;
            }
            initializeProFeatureTooltips();
        });
    }
    
    // Return public API
    return {
        init: init,
        initializeTooltips: initializeProFeatureTooltips
    };
})(jQuery);

// Auto-initialize when document is ready
jQuery(document).ready(function() {
    if (window.mementorTTSDebug) window.mementorTTSDebug.log('Document ready - initializing tooltips');
    MementorTTSTooltips.init();
});

// Also try to initialize after a short delay in case of timing issues
jQuery(window).on('load', function() {
    setTimeout(function() {
        if (window.mementorTTSDebug) window.mementorTTSDebug.log('Window load - re-initializing tooltips');
        MementorTTSTooltips.initializeTooltips();
    }, 500);
});
