(function($) {
    'use strict';

    // Make MementorAudioPlayer available globally
    window.MementorAudioPlayer = class {
        constructor(container) {
            // Check if already initialized using a more specific data attribute
            if (container.querySelector('.mementor-tts-custom-controls').dataset.playerInitialized === 'true') {
                return;
            }

            this.container = container;
            this.audio = container.querySelector('audio');
            this.isLoading = true;
            this.isMuted = false;
            this.currentSpeed = 1.0;

            // Get existing controls
            const controls = container.querySelector('.mementor-tts-custom-controls');

            // Get control elements
            this.playButton = controls.querySelector('.mementor-tts-play-button');
            this.timeDisplay = controls.querySelector('.mementor-tts-time-display');
            this.progressContainer = controls.querySelector('.mementor-tts-progress-container');
            this.progressBar = controls.querySelector('.mementor-tts-progress-bar');
            this.durationDisplay = controls.querySelector('.mementor-tts-duration-display');
            this.volumeButton = controls.querySelector('.mementor-tts-volume-button');
            this.speedButton = controls.querySelector('.mementor-tts-speed-button');
            this.downloadButton = controls.querySelector('.mementor-tts-download-button');
            this.infoButton = controls.querySelector('.mementor-tts-info-button');
            this.infoPopup = container.querySelector('.mementor-tts-info-popup');

            // Initialize state
            this.isPlaying = false;
            this.isInfoVisible = false;

            // Apply play button background based on setting
            const showPlayBg = this.container.dataset.showPlayBg === 'true';
            if (!showPlayBg && this.playButton) {
                this.playButton.classList.add('no-background');
            }

            if (this.audio) {
                // Set initial volume
                this.audio.volume = 1.0;

                // Set initial playback rate
                this.audio.playbackRate = this.currentSpeed;

                // Force load the audio
                this.audio.load();

                // Add loadeddata event listener
                this.audio.addEventListener('loadeddata', () => {
                    this.isLoading = false;
                    if (this.playButton) {
                        this.playButton.disabled = false;
                    }
                });

                // Add canplaythrough event listener
                this.audio.addEventListener('canplaythrough', () => {
                    this.isLoading = false;
                    if (this.playButton) {
                        this.playButton.disabled = false;
                    }
                });

                // Add error listener
                this.audio.addEventListener('error', (e) => {
                    if (window.mementorTTSDebug) { window.mementorTTSDebug.error('Audio loading error:', e); window.mementorTTSDebug.error('Error code:', this.audio.error?.code); window.mementorTTSDebug.error('Error message:', this.audio.error?.message); }
                    this.isLoading = false;
                    if (this.playButton) {
                        this.playButton.disabled = true;
                    }
                });

                // Setup event listeners
                this.setupAudioEventListeners();
                this.setupInfoButtonListeners();
            }

            // Mark controls as initialized
            controls.dataset.playerInitialized = 'true';
        }

        setupAudioEventListeners() {
            if (!this.audio) {
                if (window.mementorTTSDebug) window.mementorTTSDebug.error('No audio element found');
                return;
            }

            // Update duration when metadata is loaded
            this.audio.addEventListener('loadedmetadata', () => {
                if (this.audio.duration && !isNaN(this.audio.duration)) {
                    this.durationDisplay.textContent = this.formatTime(Math.floor(this.audio.duration));
                }
            });

            // Play/Pause button click
            if (this.playButton) {
                this.playButton.addEventListener('click', () => {
                    if (this.isLoading) return;

                    if (!this.isPlaying) {
                        if (this.audio.currentTime >= this.audio.duration) {
                            this.audio.currentTime = 0;
                        }

                        const playPromise = this.audio.play();
                        
                        if (playPromise !== undefined) {
                            playPromise
                                .then(() => {
                                    this.isPlaying = true;
                                    this.playButton.innerHTML = '<span class="dashicons dashicons-controls-pause"></span>';
                                })
                                .catch(error => {
                                    if (window.mementorTTSDebug) window.mementorTTSDebug.error('Play error:', error);
                                    this.isPlaying = false;
                                    this.playButton.innerHTML = '<span class="dashicons dashicons-controls-play"></span>';
                                });
                        }
                    } else {
                        this.audio.pause();
                        this.isPlaying = false;
                        this.playButton.innerHTML = '<span class="dashicons dashicons-controls-play"></span>';
                    }
                });
            }

            // Speed button click
            if (this.speedButton) {
                this.speedButton.addEventListener('click', () => {
                    const speeds = [0.5, 0.75, 1.0, 1.25, 1.5, 2.0];
                    const currentIndex = speeds.indexOf(this.currentSpeed);
                    const nextIndex = (currentIndex + 1) % speeds.length;
                    this.currentSpeed = speeds[nextIndex];
                    this.audio.playbackRate = this.currentSpeed;
                    this.speedButton.textContent = `${this.currentSpeed}x`;
                });
            }

            // Download button click
            if (this.downloadButton) {
                this.downloadButton.addEventListener('click', () => {
                    const audioSrc = this.audio.querySelector('source').src;
                    const link = document.createElement('a');
                    link.href = audioSrc;
                    link.download = 'audio.mp3';
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                });
            }

            // Volume button click
            if (this.volumeButton) {
                this.volumeButton.addEventListener('click', () => {
                    if (this.audio.volume > 0) {
                        this.previousVolume = this.audio.volume;
                        this.audio.volume = 0;
                        this.isMuted = true;
                        this.volumeButton.innerHTML = '<span class="dashicons dashicons-controls-volumeoff"></span>';
                    } else {
                        this.audio.volume = this.previousVolume || 1.0;
                        this.isMuted = false;
                        this.volumeButton.innerHTML = '<span class="dashicons dashicons-controls-volumeon"></span>';
                    }
                });
            }

            // Add ended event listener
            this.audio.addEventListener('ended', () => {
                this.isPlaying = false;
                this.playButton.innerHTML = '<span class="dashicons dashicons-controls-play"></span>';
            });

            // Add pause event listener
            this.audio.addEventListener('pause', () => {
                this.isPlaying = false;
                this.playButton.innerHTML = '<span class="dashicons dashicons-controls-play"></span>';
            });

            // Add play event listener
            this.audio.addEventListener('play', () => {
                this.isPlaying = true;
                this.playButton.innerHTML = '<span class="dashicons dashicons-controls-pause"></span>';
            });

            // Update time and progress bar
            this.audio.addEventListener('timeupdate', () => {
                const currentTime = Math.floor(this.audio.currentTime);
                const progress = (this.audio.currentTime / this.audio.duration) * 100;

                this.timeDisplay.textContent = this.formatTime(currentTime);
                this.progressBar.style.width = `${progress}%`;
            });

            // Progress bar click handling
            if (this.progressContainer) {
                this.progressContainer.addEventListener('click', (e) => {
                    const rect = this.progressContainer.getBoundingClientRect();
                    const pos = (e.clientX - rect.left) / rect.width;
                    this.audio.currentTime = pos * this.audio.duration;
                });
            }
        }

        setupInfoButtonListeners() {
            if (this.infoButton) {
                // Find or create the info popup
                let infoPopup = document.querySelector('.mementor-tts-info-popup');
                
                // Create popup if it doesn't exist
                if (!infoPopup) {
                    infoPopup = document.createElement('div');
                    infoPopup.className = 'mementor-tts-info-popup';
                    
                    const infoText = document.createElement('p');
                    infoText.innerHTML = 'Generated with Mementor\'s <a href="https://mementor.no/en/wordpress-plugins/text-to-speech/" target="_blank" rel="noopener"><strong>Text to Speech for WordPress plugin</strong></a>, using <a href="https://try.elevenlabs.io/mementor" target="_blank" rel="noopener"><strong>ElevenLabs</strong></a> technology.';
                    infoPopup.appendChild(infoText);
                    
                    // Append to body
                    document.body.appendChild(infoPopup);
                }
                
                this.infoPopup = infoPopup;
                this.isInfoVisible = false;

                this.infoButton.addEventListener('click', () => {
                    this.isInfoVisible = !this.isInfoVisible;
                    
                    if (this.isInfoVisible) {
                        // Remove all position classes first
                        infoPopup.classList.remove('position-top-left', 'position-top-center', 'position-top-right');
                        
                        // Clear any inline styles that might be present
                        infoPopup.style.left = '';
                        infoPopup.style.top = '';
                        infoPopup.style.right = '';
                        infoPopup.style.bottom = '';
                        
                        // Get button position in viewport
                        const buttonRect = this.infoButton.getBoundingClientRect();
                        
                        // Ensure popup is in the body
                        if (!infoPopup.parentElement || infoPopup.parentElement !== document.body) {
                            document.body.appendChild(infoPopup);
                        }
                        
                        // Position using CSS variables
                        infoPopup.style.setProperty('--button-x', `${buttonRect.left}px`);
                        infoPopup.style.setProperty('--button-y', `${buttonRect.top}px`);
                        infoPopup.style.setProperty('--button-width', `${buttonRect.width}px`);
                        infoPopup.style.setProperty('--button-right', `${buttonRect.right}px`);
                        
                        // Position using CSS classes
                        if (buttonRect.left < 150) {
                            // Button is near left edge
                            infoPopup.classList.add('position-top-left');
                        } else if (buttonRect.right > window.innerWidth - 150) {
                            // Button is near right edge
                            infoPopup.classList.add('position-top-right');
                        } else {
                            // Button is in center area
                            infoPopup.classList.add('position-top-center');
                        }
                        
                        // Show the popup
                        infoPopup.classList.add('tooltip-visible');
                    } else {
                        infoPopup.classList.remove('tooltip-visible');
                    }
                });

                // Close popup when clicking outside
                document.addEventListener('click', (e) => {
                    if (this.isInfoVisible && !this.infoButton.contains(e.target) && !this.infoPopup.contains(e.target)) {
                        this.isInfoVisible = false;
                        this.infoPopup.classList.remove('tooltip-visible');
                    }
                });
            }
        }

        formatTime(seconds) {
            const minutes = Math.floor(seconds / 60);
            seconds = seconds % 60;
            return `${minutes}:${seconds.toString().padStart(2, '0')}`;
        }
    }

    // Initialize players when document is ready
    $(document).ready(function() {
        // Function to initialize a player
        function initializePlayer(player) {
            // Check if player is already initialized
            if (player.querySelector('.mementor-tts-custom-controls').dataset.playerInitialized === 'true') {
                return;
            }
            
            // Initialize the player
            new MementorAudioPlayer(player);
            
            // Mark as initialized
            player.querySelector('.mementor-tts-custom-controls').dataset.playerInitialized = 'true';
        }

        // Initialize visible players
        function initializeVisiblePlayers() {
            const players = document.querySelectorAll('.mementor-tts-player');
            players.forEach(player => {
                const tabContent = player.closest('.mementor-tts-tab-content');
                if (!tabContent || getComputedStyle(tabContent).display !== 'none') {
                    initializePlayer(player);
                }
            });
        }

        // Initialize players on page load
        initializeVisiblePlayers();

        // Initialize players when tabs are switched
        $('.mementor-tts-tabs a').on('click', function() {
            const tabId = $(this).data('tab');
            const tabContent = document.getElementById(tabId);
            
            if (tabContent) {
                setTimeout(() => {
                    const tabPlayers = tabContent.querySelectorAll('.mementor-tts-player');
                    tabPlayers.forEach(player => {
                        initializePlayer(player);
                    });
                }, 100); // Small delay to ensure tab content is visible
            }
        });

        // Re-initialize players when settings are saved
        $(document).on('mementor_tts_settings_saved', function() {
            initializeVisiblePlayers();
        });
    });

})(jQuery);
