/**
 * Handle player positioning and prevent duplicates
 *
 * @package    Mementor_TTS
 * @since      1.0.0
 */

(function() {
    'use strict';
    
    // We now rely on the centralized debug logic in mementor-tts-debug-settings.js
    // The global mementorTTSDebugEnabled variable should already be set
    // The global mementorTTSDebug function should already be defined
    
    // Create a safe wrapper for debug logging
    var safeDebug = function() {
        if (typeof window.mementorTTSDebug === 'function') {
            window.mementorTTSDebug.apply(window, arguments);
        }
    };
    
    // Log initialization if debug is enabled
    safeDebug('Player position script initialized');
    
    // IMPORTANT: Player positioning is now handled by PHP hooks
    // JavaScript cleanup is disabled to prevent conflicts
    safeDebug('Player positioning handled by PHP hooks - JavaScript cleanup disabled');
    
    document.addEventListener('DOMContentLoaded', function() {
        safeDebug('DOM Content Loaded');
        
        // Don't do any JavaScript positioning for now
        // The PHP positioning should be sufficient
        safeDebug('JavaScript positioning disabled - using PHP positioning only');
        
        setTimeout(function() {
            
            // Check if any players are hidden
            var allPlayers = document.querySelectorAll('.mementor-tts-player-container');
            allPlayers.forEach(function(player) {
                var styles = window.getComputedStyle(player);
                if (styles.display === 'none' || styles.visibility === 'hidden' || styles.opacity === '0') {
                    safeDebug('WARNING: Player is hidden by CSS - display: ' + styles.display + ', visibility: ' + styles.visibility + ', opacity: ' + styles.opacity);
                }
            });
            
            // Still handle player width settings
            handlePlayerWidth();
            
            // Initialize width controls for live preview
            initializeWidthControls();
            
            // Reinitialize play buttons
            reinitializePlayButtons();
        }, 500); // 500ms delay for Elementor content
    });
    
    /**
     * Handle before title positioning
     */
    function handleBeforeTitlePositioning() {
        safeDebug('handleBeforeTitlePositioning called');
        
        // Log page URL for debugging
        safeDebug('Current page URL: ' + window.location.href);
        
        // Find all players on the page
        var players = document.querySelectorAll('.mementor-tts-player-container');
        safeDebug('Found ' + players.length + ' players');
        
        if (players.length === 0) {
            safeDebug('No players found, exiting');
            
            // Check if there's player HTML in the page that wasn't rendered
            var bodyHTML = document.body.innerHTML;
            if (bodyHTML.indexOf('mementor-tts-player-container') > -1) {
                safeDebug('Player HTML found in page source but not rendered as DOM element');
            }
            
            return;
        }
        
        // Find the main title element
        var titleElement = null;
        var titleSelectors = [
            'h1.entry-title',
            'h1.elementor-heading-title', // Elementor specific
            '.elementor-widget-heading h1', // Another Elementor selector
            '.elementor-widget-theme-post-title h1', // Elementor post title widget
            '.entry-header h1',
            '.post-title',
            'article h1:first-of-type',
            '.page-title',
            'h1.wp-block-post-title' // Block editor
        ];
        
        // Debug: Log all h1 elements on the page
        var allH1s = document.querySelectorAll('h1');
        safeDebug('Total H1 elements on page: ' + allH1s.length);
        allH1s.forEach(function(h1, index) {
            safeDebug('H1 #' + index + ' classes: ' + h1.className + ', text: ' + h1.textContent.substring(0, 50));
        });
        
        for (var i = 0; i < titleSelectors.length; i++) {
            var elements = document.querySelectorAll(titleSelectors[i]);
            if (elements.length > 0) {
                titleElement = elements[0];
                safeDebug('Found title element with selector: ' + titleSelectors[i]);
                break;
            }
        }
        
        if (!titleElement) {
            safeDebug('No title element found with standard selectors, trying alternative approach');
            
            // Try to find content container and insert at the beginning
            var contentSelectors = [
                '.elementor-widget-container',
                '.elementor-section',
                '.entry-content',
                '.post-content',
                'article .content',
                '.site-content article',
                'main article'
            ];
            
            var contentElement = null;
            for (var j = 0; j < contentSelectors.length; j++) {
                var elements = document.querySelectorAll(contentSelectors[j]);
                if (elements.length > 0) {
                    contentElement = elements[0];
                    safeDebug('Found content element with selector: ' + contentSelectors[j]);
                    break;
                }
            }
            
            if (!contentElement) {
                safeDebug('No content element found either, cannot position player');
                return;
            }
            
            // Remove all players except the first one
            for (var i = 1; i < players.length; i++) {
                safeDebug('Removing duplicate player ' + i);
                if (players[i].parentNode) {
                    players[i].parentNode.removeChild(players[i]);
                }
            }
            
            // Move the first player to the beginning of content
            var player = players[0];
            player.classList.add('mementor-tts-before-title-js');
            
            // Insert at the beginning of content
            if (contentElement.firstChild) {
                contentElement.insertBefore(player, contentElement.firstChild);
            } else {
                contentElement.appendChild(player);
            }
            
            safeDebug('Positioned player at beginning of content as fallback');
            return;
        }
        
        // Remove all players except the first one
        for (var i = 1; i < players.length; i++) {
            safeDebug('Removing duplicate player ' + i);
            if (players[i].parentNode) {
                players[i].parentNode.removeChild(players[i]);
            }
        }
        
        // Move the first player before the title
        var player = players[0];
        
        // Add class to identify positioned player
        player.classList.add('mementor-tts-before-title-js');
        
        // Insert player before title
        if (titleElement.parentNode) {
            safeDebug('Inserting player before title element');
            titleElement.parentNode.insertBefore(player, titleElement);
        }
    }
    
    /**
     * Reinitialize the play button click functionality for all players
     * This ensures play buttons work after player position changes
     */
    function reinitializePlayButtons() {
        safeDebug('Reinitializing play buttons');
        
        // Find all player elements
        var players = document.querySelectorAll('.mementor-tts-player');
        
        players.forEach(function(player) {
            var audio = player.querySelector('audio');
            var playButton = player.querySelector('.mementor-tts-play-button');
            
            if (!audio || !playButton) return;
            
            // First, ensure audio is properly loaded with metadata
            if (audio.readyState === 0) {
                audio.load();
            }
            
            // Remove any existing event listeners by cloning the button
            var newPlayButton = playButton.cloneNode(true);
            playButton.parentNode.replaceChild(newPlayButton, playButton);
            playButton = newPlayButton;
            
            // Check if this is a shortcode player needing generation
            const isShortcodePending = player.matches('.mementor-tts-player[data-status="pending"][data-text]');

            // Only add the generic play/pause listener if it's NOT a pending shortcode
            if (!isShortcodePending) {
                playButton.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation(); // Prevent event bubbling
                    
                    safeDebug('Play button clicked');
                    
                    if (audio.paused) {
                        // Make sure source is set
                        if (!audio.src && audio.querySelector('source')) {
                            audio.src = audio.querySelector('source').src;
                        }
                        
                        // Force audio to load if not already loaded
                        if (audio.readyState === 0) {
                            audio.load();
                        }
                        
                        // Play the audio with enhanced error handling
                        try {
                            var playPromise = audio.play();
                            
                            if (playPromise !== undefined) {
                                playPromise.then(function() {
                                    // Playback started successfully
                                    safeDebug('Audio playback started successfully');
                                    var icon = playButton.querySelector('.dashicons');
                                    if (icon) {
                                        icon.classList.remove('dashicons-controls-play', 'mementor-dashicons-controls-play');
                                        icon.classList.add('dashicons-controls-pause', 'mementor-dashicons-controls-pause');
                                    }
                                }).catch(function(error) {
                                    if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('Audio playback was prevented:', error); }
                                    
                                    // Try one more time with a slight delay
                                    setTimeout(function() {
                                        audio.play().catch(function(retryError) {
                                            if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('Retry playback failed:', retryError); }
                                        });
                                    }, 100);
                                });
                            } else {
                                // Older browsers might not return a promise
                                safeDebug('Browser did not return play promise, assuming playback started');
                                var icon = playButton.querySelector('.dashicons');
                                if (icon) {
                                    icon.classList.remove('dashicons-controls-play', 'mementor-dashicons-controls-play');
                                    icon.classList.add('dashicons-controls-pause', 'mementor-dashicons-controls-pause');
                                }
                            }
                        } catch(error) {
                            if (window.mementorTTSDebugSettings && window.mementorTTSDebugSettings.isDebug) { console.error('Exception during play attempt:', error); }
                        }
                    } else {
                        // Pause the audio
                        audio.pause();
                        var icon = playButton.querySelector('.dashicons');
                        if (icon) {
                            icon.classList.remove('dashicons-controls-pause', 'mementor-dashicons-controls-pause');
                            icon.classList.add('dashicons-controls-play', 'mementor-dashicons-controls-play');
                        }
                    }
                });
            }
            
            // Add play/pause event listeners to audio element to update button state
            // Note: We don't add debug logging here as it's already handled in the main player script
            // Check if these specific position event listeners have already been added
            if (!audio._positionListenersSetup) {
                audio._positionListenersSetup = true;
                
                audio.addEventListener('play', function() {
                    var icon = playButton.querySelector('.dashicons');
                    if (icon) {
                        icon.classList.remove('dashicons-controls-play', 'mementor-dashicons-controls-play');
                        icon.classList.add('dashicons-controls-pause', 'mementor-dashicons-controls-pause');
                    }
                });
                
                audio.addEventListener('pause', function() {
                    var icon = playButton.querySelector('.dashicons');
                    if (icon) {
                        icon.classList.remove('dashicons-controls-pause', 'mementor-dashicons-controls-pause');
                        icon.classList.add('dashicons-controls-play', 'mementor-dashicons-controls-play');
                    }
                });
                
                audio.addEventListener('ended', function() {
                    var icon = playButton.querySelector('.dashicons');
                    if (icon) {
                        icon.classList.remove('dashicons-controls-pause', 'mementor-dashicons-controls-pause');
                        icon.classList.add('dashicons-controls-play', 'mementor-dashicons-controls-play');
                    }
                    audio.currentTime = 0; // Reset to beginning
                });
            }
        });
    }
    
    /**
     * Master function to clean up duplicate players across the entire page
     * This function will be called multiple times to ensure we catch all duplicates
     */
    function cleanupDuplicatePlayers() {
        // Get all player containers, EXCLUDING shortcode players
        var allPlayers = document.querySelectorAll('.mementor-tts-player-container:not([data-player-type="shortcode"])');
        
        // First pass - categorize players by position (only auto-inserted players)
        var beforeTitlePlayer = null;
        var afterTitleBeforeExcerptPlayer = null;
        var afterTitleAfterExcerptPlayer = null;
        var afterTitlePlayer = null;
        var inContentPlayer = null;
        
        allPlayers.forEach(function(player) {
            if (player.classList.contains('mementor-tts-before-title') || 
                player.classList.contains('mementor-tts-before-title-js')) {
                beforeTitlePlayer = beforeTitlePlayer || player;
            } else if (player.classList.contains('mementor-tts-after-title-before-excerpt')) {
                afterTitleBeforeExcerptPlayer = afterTitleBeforeExcerptPlayer || player;
            } else if (player.classList.contains('mementor-tts-after-title-after-excerpt')) {
                afterTitleAfterExcerptPlayer = afterTitleAfterExcerptPlayer || player;
            } else if (player.classList.contains('mementor-tts-after-title') || 
                       player.classList.contains('mementor-tts-after-title-js')) {
                afterTitlePlayer = afterTitlePlayer || player;
            } else if (player.classList.contains('mementor-tts-after-content')) {
                inContentPlayer = inContentPlayer || player;
            }
        });
        
        // Second pass - remove duplicates based on position setting
        if (typeof mementorTTSPlayerPosition !== 'undefined') {
            var position = mementorTTSPlayerPosition.position;
            
            allPlayers.forEach(function(player) {
                // Skip if this is our keeper player based on position
                if ((position === 'before_title' && player === beforeTitlePlayer) ||
                    (position === 'after_title_before_excerpt' && player === afterTitleBeforeExcerptPlayer) ||
                    (position === 'after_title_after_excerpt' && player === afterTitleAfterExcerptPlayer) ||
                    (position === 'after_title' && player === afterTitlePlayer) ||
                    (position === 'after_content' && player === inContentPlayer)) {
                    return;
                }
                
                // Remove duplicate (but never remove shortcode players)
                if (player && player.parentNode && player.getAttribute('data-player-type') !== 'shortcode') {
                    safeDebug('Removing duplicate player with class:', player.className);
                    player.parentNode.removeChild(player);
                }
            });
        } else {
            // If no position setting found, keep only the first auto-inserted player
            // Never remove shortcode players
            for (var i = 1; i < allPlayers.length; i++) {
                if (allPlayers[i] && allPlayers[i].parentNode && 
                    allPlayers[i].getAttribute('data-player-type') !== 'shortcode') {
                    safeDebug('Removing extra player (no position setting found)');
                    allPlayers[i].parentNode.removeChild(allPlayers[i]);
                }
            }
        }
        
        // After cleanup, reinitialize the remaining players
        reinitializePlayButtons();
    }
    
    /**
     * Initialize a player's audio element and duration display
     */
    function initializePlayer(playerElement) {
        if (!playerElement) return;
        
        var audioElement = playerElement.querySelector('audio');
        var durationDisplay = playerElement.querySelector('.mementor-tts-duration-display');
        
        if (audioElement && durationDisplay) {
            // Force audio element to load metadata
            audioElement.preload = "metadata";
            
            // Add event listener for when metadata is loaded
            audioElement.addEventListener('loadedmetadata', function() {
                if (audioElement.duration && !isNaN(audioElement.duration)) {
                    var minutes = Math.floor(audioElement.duration / 60);
                    var seconds = Math.floor(audioElement.duration % 60);
                    durationDisplay.textContent = minutes + ':' + (seconds < 10 ? '0' : '') + seconds;
                    safeDebug('Successfully initialized player with duration: ' + durationDisplay.textContent);
                }
            });
            
            // If metadata is already loaded, update the duration display
            if (audioElement.readyState >= 1 && audioElement.duration && !isNaN(audioElement.duration)) {
                var minutes = Math.floor(audioElement.duration / 60);
                var seconds = Math.floor(audioElement.duration % 60);
                durationDisplay.textContent = minutes + ':' + (seconds < 10 ? '0' : '') + seconds;
                safeDebug('Updated player with existing duration: ' + durationDisplay.textContent);
            }
            
            // Additional fallback: Try to load metadata if not already loaded
            if (audioElement.readyState === 0) {
                safeDebug('Forcing audio load to get metadata');
                audioElement.load();
            }
            
            // Fallback: Check duration periodically until it's available
            var durationCheckAttempts = 0;
            var maxAttempts = 10;
            var durationCheckInterval = setInterval(function() {
                if (durationCheckAttempts >= maxAttempts) {
                    clearInterval(durationCheckInterval);
                    safeDebug('Max duration check attempts reached');
                    return;
                }
                
                if (audioElement.duration && !isNaN(audioElement.duration)) {
                    var minutes = Math.floor(audioElement.duration / 60);
                    var seconds = Math.floor(audioElement.duration % 60);
                    durationDisplay.textContent = minutes + ':' + (seconds < 10 ? '0' : '') + seconds;
                    safeDebug('Duration updated via interval check: ' + durationDisplay.textContent);
                    clearInterval(durationCheckInterval);
                }
                
                durationCheckAttempts++;
            }, 500);
        }
    }
    
    /**
     * Hide any player containers that might have been rendered on non-singular pages
     */
    function hidePlayersOnNonSingularPages() {
        var playerContainers = document.querySelectorAll('.mementor-tts-player-container');
        
        if (playerContainers.length > 0) {
            safeDebug('Removing ' + playerContainers.length + ' player containers on non-singular page');
            
            playerContainers.forEach(function(container) {
                if (container && container.parentNode) {
                    container.parentNode.removeChild(container);
                }
            });
        }
    }
    
    /**
     * Log debugging information
     */
    function logDebugInfo() {
        safeDebug('Mementor TTS Player Position script loaded');
        
        // Check if we have any plain text HTML showing in the page
        var bodyText = document.body.innerText;
        if (bodyText.indexOf('<div class="mementor-tts-player-container') > -1) {
            safeDebug('Found unrendered HTML in page text. This indicates a WordPress filter issue.');
            
            // Check specifically for the player HTML
            var playerPattern = /<div class="mementor-tts-player-container[^>]*>[\s\S]*?<\/div>/g;
            var matches = bodyText.match(playerPattern);
            
            if (matches && matches.length) {
                safeDebug('Found ' + matches.length + ' instances of unrendered player HTML.');
                
                // Find if the text is within a specific element
                var elements = document.querySelectorAll('h1, h2, .entry-title, .post-title, article .title');
                
                elements.forEach(function(element) {
                    var elementText = element.innerText;
                    if (elementText.indexOf('<div class="mementor-tts-player-container') > -1) {
                        safeDebug('Found unrendered HTML in element:', element);
                        
                        // Find all matches in this element
                        var elementMatches = elementText.match(playerPattern);
                        if (elementMatches && elementMatches.length) {
                            safeDebug('Found ' + elementMatches.length + ' matches in this element.');
                            
                            // We'll create proper HTML elements for each match
                            elementMatches.forEach(function(match) {
                                safeDebug('Processing match:', match.substring(0, 50) + '...');
                                
                                // Create temporary container to parse the HTML
                                var tempContainer = document.createElement('div');
                                tempContainer.innerHTML = match;
                                
                                // Remove the HTML from the element's text
                                if (element.childNodes.length === 1 && element.childNodes[0].nodeType === 3) {
                                    // It's just a single text node, we can replace it directly
                                    element.innerText = element.innerText.replace(match, '');
                                } else {
                                    // It's more complex, we need to find the text node with our HTML
                                    element.childNodes.forEach(function(node) {
                                        if (node.nodeType === 3 && node.textContent.indexOf('<div class="mementor-tts-player-container') > -1) {
                                            node.textContent = node.textContent.replace(match, '');
                                        }
                                    });
                                }
                                
                                // Insert the rendered HTML before the element
                                element.parentNode.insertBefore(tempContainer.firstChild, element);
                                
                                safeDebug('Fix applied successfully for this match.');
                            });
                        }
                    }
                });
                
                // If we don't find specific elements, search the whole document
                if (elements.length === 0) {
                    safeDebug('No specific elements found, searching entire document for HTML text');
                    
                    // Select all text nodes in the document
                    var allTextNodes = [];
                    var walk = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null, false);
                    var node;
                    while(node = walk.nextNode()) {
                        if (node.nodeValue && node.nodeValue.indexOf('<div class="mementor-tts-player-container') > -1) {
                            allTextNodes.push(node);
                        }
                    }
                    
                    safeDebug('Found ' + allTextNodes.length + ' text nodes with player HTML');
                    
                    // Process each text node
                    allTextNodes.forEach(function(textNode) {
                        var nodeText = textNode.nodeValue;
                        var nodeMatches = nodeText.match(playerPattern);
                        
                        if (nodeMatches && nodeMatches.length) {
                            safeDebug('Processing node with matches');
                            
                            nodeMatches.forEach(function(match) {
                                // Create temporary container
                                var tempContainer = document.createElement('div');
                                tempContainer.innerHTML = match;
                                
                                // Replace the HTML in the text node
                                textNode.nodeValue = textNode.nodeValue.replace(match, '');
                                
                                // Insert the player before the parent of the text node
                                textNode.parentNode.parentNode.insertBefore(tempContainer.firstChild, textNode.parentNode);
                            });
                        }
                    });
                }
            }
        }
    }
    
    /**
     * Handle 'before_title' position - ensure only one player is shown
     */
    function handleBeforeTitlePosition() {
        // First ensure we remove any duplicate players
        var beforeTitlePlayers = document.querySelectorAll('.mementor-tts-before-title-js');
        if (beforeTitlePlayers.length > 1) {
            // Keep only the first player and remove others
            for (var i = 1; i < beforeTitlePlayers.length; i++) {
                if (beforeTitlePlayers[i] && beforeTitlePlayers[i].parentNode) {
                    beforeTitlePlayers[i].parentNode.removeChild(beforeTitlePlayers[i]);
                }
            }
        }

        // Check for ANY players on the page, regardless of class
        var allPlayers = document.querySelectorAll('.mementor-tts-player-container');
        if (allPlayers.length > 1) {
            safeDebug('Multiple players detected on page (' + allPlayers.length + ')');
            
            // First check if any player has proper duration
            var workingPlayerFound = false;
            var workingPlayer = null;
            
            allPlayers.forEach(function(player) {
                var durationDisplay = player.querySelector('.mementor-tts-duration-display');
                if (durationDisplay && durationDisplay.textContent !== '0:00') {
                    workingPlayerFound = true;
                    workingPlayer = player;
                    safeDebug('Found working player with duration');
                }
            });
            
            // If we found a working player, remove all others
            if (workingPlayerFound && workingPlayer) {
                allPlayers.forEach(function(player) {
                    if (player !== workingPlayer) {
                        safeDebug('Removing duplicate player');
                        if (player.parentNode) {
                            player.parentNode.removeChild(player);
                        }
                    }
                });
            } 
            // If no working players found but we have multiple players, keep only one
            else {
                // Keep the first player and remove all others
                for (var i = 1; i < allPlayers.length; i++) {
                    safeDebug('Removing extra player (no working players found)');
                    if (allPlayers[i] && allPlayers[i].parentNode) {
                        allPlayers[i].parentNode.removeChild(allPlayers[i]);
                    }
                }
            }
        }

        // If we already have a player from PHP insertion, don't add another one via JS
        var existingPlayers = document.querySelectorAll('.mementor-tts-before-title');
        if (existingPlayers.length > 1) {
            // Keep only the first one
            for (var i = 1; i < existingPlayers.length; i++) {
                if (existingPlayers[i] && existingPlayers[i].parentNode) {
                    existingPlayers[i].parentNode.removeChild(existingPlayers[i]);
                }
            }
        }
    }
    
    /**
     * Handle 'after_content' position - ensure only one player is shown
     */
    function handleAfterContentPosition() {
        // Ensure we only have one after-content player by removing duplicates
        var afterContentPlayers = document.querySelectorAll('.mementor-tts-after-content');
        if (afterContentPlayers.length > 1) {
            // Keep only the first player and remove others
            for (var i = 1; i < afterContentPlayers.length; i++) {
                if (afterContentPlayers[i] && afterContentPlayers[i].parentNode) {
                    afterContentPlayers[i].parentNode.removeChild(afterContentPlayers[i]);
                }
            }
        }
        
        // Also remove any players that might have been added twice without the specific class
        var allPlayers = document.querySelectorAll('.mementor-tts-player');
        if (allPlayers.length > 1) {
            // Check if they're in the same location (after content)
            var contentElements = document.querySelectorAll('.entry-content, .post-content, article .content, .site-content, .elementor-widget-theme-post-content');
            if (contentElements.length > 0) {
                var contentElement = contentElements[0];
                var playersInContent = contentElement.querySelectorAll('.mementor-tts-player');
                
                // If we have multiple players in the content, remove extras
                if (playersInContent.length > 1) {
                    // Find the last player (which should be after content)
                    var lastPlayer = playersInContent[playersInContent.length - 1];
                    
                    // Keep the last player and remove any earlier players in the content
                    for (var i = 0; i < playersInContent.length - 1; i++) {
                        var playerContainer = playersInContent[i].closest('.mementor-tts-player-container');
                        if (playerContainer && playerContainer.parentNode) {
                            playerContainer.parentNode.removeChild(playerContainer);
                        }
                    }
                }
            }
        }
    }
    
    /**
     * Handle 'after_title' position - ensure only one player is shown
     */
    function handleAfterTitlePosition() {
        // Ensure we only have one after-title player by looking at specific class
        var afterTitlePlayers = document.querySelectorAll('.mementor-tts-after-title-js');
        if (afterTitlePlayers.length > 1) {
            safeDebug('Found multiple after-title players, keeping only first one');
            // Keep only the first player and remove others
            for (var i = 1; i < afterTitlePlayers.length; i++) {
                if (afterTitlePlayers[i] && afterTitlePlayers[i].parentNode) {
                    afterTitlePlayers[i].parentNode.removeChild(afterTitlePlayers[i]);
                }
            }
        }
        
        // Check for unclassed players in header area
        var headerElements = document.querySelectorAll('.entry-header, .post-header, .page-header, .article-header');
        if (headerElements.length > 0) {
            headerElements.forEach(function(headerElement) {
                var playersInHeader = headerElement.querySelectorAll('.mementor-tts-player-container');
                
                // If we have multiple players in the header, remove extras
                if (playersInHeader.length > 1) {
                    safeDebug('Found multiple players in header, keeping only first one');
                    // Keep only the first player in the header
                    for (var i = 1; i < playersInHeader.length; i++) {
                        if (playersInHeader[i] && playersInHeader[i].parentNode) {
                            playersInHeader[i].parentNode.removeChild(playersInHeader[i]);
                        }
                    }
                }
            });
        }
        
        // Also check if the player is missing but we need to add it
        if (afterTitlePlayers.length === 0) {
            // Check if we have "after_title" as our position
            if (typeof mementorTTSPlayerPosition !== 'undefined' && 
                mementorTTSPlayerPosition.position === 'after_title') {
                
                safeDebug('After title position is set but no player found. The PHP insertion might have failed.');
                
                // We'll check if there's a player added elsewhere we can move
                var otherPlayers = document.querySelectorAll('.mementor-tts-player-container:not(.mementor-tts-after-title-js):not(.mementor-tts-before-title):not(.mementor-tts-before-title-js):not(.mementor-tts-after-content)');
                
                if (otherPlayers.length > 0) {
                    safeDebug('Found a player elsewhere that can be moved after title');
                    
                    // Find the title element
                    var titleElement = null;
                    var titleSelectors = [
                        'h1.entry-title', 
                        '.entry-header h1', 
                        '.post-title', 
                        'article h1:first-of-type',
                        '.page-title'
                    ];
                    
                    // Try each selector until we find a match
                    for (var i = 0; i < titleSelectors.length; i++) {
                        var elements = document.querySelectorAll(titleSelectors[i]);
                        if (elements.length > 0) {
                            titleElement = elements[0];
                            break;
                        }
                    }
                    
                    if (titleElement) {
                        // Move the first found player after the title
                        var playerToMove = otherPlayers[0];
                        playerToMove.classList.add('mementor-tts-after-title-js');
                        
                        if (titleElement.nextSibling) {
                            titleElement.parentNode.insertBefore(playerToMove, titleElement.nextSibling);
                        } else {
                            titleElement.parentNode.appendChild(playerToMove);
                        }
                        
                        safeDebug('Successfully moved player after title');
                    }
                }
            }
        }
    }
    
    /**
     * Handle player width based on settings
     */
    function handlePlayerWidth() {
        // Get all player containers, including preview players
        var playerContainers = document.querySelectorAll('.mementor-tts-player-container, .mementor-tts-preview-player');
        
        playerContainers.forEach(function(container) {
            // Get width setting from data attribute or default to full width
            var widthSetting = container.dataset.width || 'full_width';
            
            // Remove any existing width classes from both container and inner player
            container.classList.remove('mementor-tts-width-500', 'mementor-tts-width-custom', 'mementor-tts-width-full');
            
            // Also handle inner player if this is a preview container
            var innerPlayer = container.querySelector('.mementor-tts-player');
            if (innerPlayer) {
                innerPlayer.classList.remove('mementor-tts-width-500', 'mementor-tts-width-custom', 'mementor-tts-width-full');
            }
            
            // Add appropriate width class to both container and inner player
            var widthClass = '';
            switch(widthSetting) {
                case 'content_width':
                    widthClass = 'mementor-tts-width-500';
                    break;
                case 'custom_width':
                    widthClass = 'mementor-tts-width-custom';
                    break;
                default:
                    widthClass = 'mementor-tts-width-full';
            }
            
            container.classList.add(widthClass);
            if (innerPlayer) {
                innerPlayer.classList.add(widthClass);
            }
            
            // Check container width and add constrained class if needed
            var containerWidth = container.offsetWidth;
            if (containerWidth < 640) {
                container.classList.add('constrained-width');
                if (innerPlayer) {
                    innerPlayer.classList.add('constrained-width');
                }
            } else {
                container.classList.remove('constrained-width');
                if (innerPlayer) {
                    innerPlayer.classList.remove('constrained-width');
                }
            }
        });
    }

    /**
     * Handle live width updates for preview player
     */
    function initializeWidthControls() {
        safeDebug('Initializing width controls');
        
        // Listen for changes to the width radio buttons
        var widthRadios = document.querySelectorAll('input[name="mementor_tts_player_width"]');
        safeDebug('Found width radio buttons:', widthRadios.length);
        
        if (widthRadios.length) {
            widthRadios.forEach(function(radio) {
                radio.addEventListener('change', function() {
                    safeDebug('Width radio changed to:', this.value);
                    var previewPlayer = document.querySelector('.mementor-tts-preview-player');
                    safeDebug('Found preview player:', previewPlayer ? 'yes' : 'no');
                    
                    if (previewPlayer) {
                        // Update the data-width attribute
                        previewPlayer.dataset.width = this.value;
                        safeDebug('Updated data-width to:', this.value);
                        // Update width classes
                        handlePlayerWidth();
                    }
                });
            });
        }

        // Listen for changes to the custom width input
        var customWidthInput = document.querySelector('input[name="mementor_tts_custom_width"]');
        safeDebug('Found custom width input:', customWidthInput ? 'yes' : 'no');
        
        if (customWidthInput) {
            ['input', 'change'].forEach(function(eventType) {
                customWidthInput.addEventListener(eventType, function() {
                    safeDebug('Custom width changed to:', this.value);
                    var previewPlayer = document.querySelector('.mementor-tts-preview-player');
                    safeDebug('Found preview player for custom width:', previewPlayer ? 'yes' : 'no');
                    
                    if (previewPlayer) {
                        // Update the custom width CSS variable
                        previewPlayer.style.setProperty('--mementor-tts-custom-width', this.value + 'px');
                        safeDebug('Updated custom width CSS variable');
                        // Also trigger width class update
                        handlePlayerWidth();
                    }
                });
            });
        }
    }
})(); 