jQuery(document).ready(function($) {
    $('.mp3-vplayer').each(function() {
        const player = $(this);
        const audio = player.find('audio')[0];
        if (!audio) return;
        
        // Parse tracks safely
        let tracks = [];
        try {
            tracks = JSON.parse(player.attr('data-tracks') || '[]');
        } catch (e) {
            console.error('MP3 VPlayer: Invalid tracks data', e);
            return;
        }
        if (!tracks.length) return;
        
        // Elements
        const playPauseBtn = player.find('.btn-play-pause');
        const iconPlay = player.find('.icon-play');
        const iconPause = player.find('.icon-pause');
        const prevBtn = player.find('.btn-previous');
        const nextBtn = player.find('.btn-next');
        const progressBar = player.find('.progress-bar');
        const progressFill = player.find('.progress-fill');
        const timeCurrent = player.find('.time-current');
        const timeDuration = player.find('.time-duration');
        const trackTitle = player.find('.track-title');
        const trackArtist = player.find('.track-artist');
        const volumeControl = player.find('.volume-control');
        const playlistItems = player.find('.playlist-item');
        
        let currentTrackIndex = 0;
        
        // Check if autoplay is enabled
        const wantAutoplay = player.find('audio').is('[autoplay]');
        
        // Set initial volume
        const startVol = volumeControl.length ? parseFloat(volumeControl.val()) : 70;
        audio.volume = isFinite(startVol) ? startVol / 100 : 0.7;
        
        // Format time helper
        function formatTime(seconds) {
            if (!isFinite(seconds) || seconds < 0) return '0:00';
            const mins = Math.floor(seconds / 60);
            const secs = Math.floor(seconds % 60);
            return mins + ':' + (secs < 10 ? '0' : '') + secs;
        }
        
        // Mark active track in playlist
        function markActiveTrack(index) {
            if (playlistItems.length === 0) return;
            playlistItems.removeClass('active is-active');
            playlistItems.eq(index).addClass('active is-active');
        }
        
        // Load track
        function loadTrack(index) {
            if (index < 0 || index >= tracks.length) return;
            
            currentTrackIndex = index;
            const track = tracks[index];
            
            audio.src = track.url;
            trackTitle.text(track.title || 'Track');
            trackArtist.text(track.artist || 'Unknown');
            
            // Update playlist UI
            markActiveTrack(index);
            
            // Reset progress
            progressFill.css('width', '0%');
            timeCurrent.text('0:00');
            timeDuration.text('0:00');
            
            // Load metadata
            audio.load();
        }
        
        // Autoplay retry logic with exponential backoff
        let retryTimers = [];
        
        function clearRetryTimers() {
            retryTimers.forEach(timer => clearTimeout(timer));
            retryTimers = [];
        }
        
        function attemptPlay() {
            const playPromise = audio.play();
            if (playPromise && typeof playPromise.then === 'function') {
                return playPromise
                    .then(() => true)
                    .catch((error) => {
                        console.log('MP3 VPlayer: Autoplay prevented by browser', error);
                        return false;
                    });
            }
            return Promise.resolve(!audio.paused);
        }
        
        function tryAutoplayWithRetries() {
            clearRetryTimers();
            
            // First immediate attempt
            attemptPlay().then(success => {
                if (success) return;
                
                // If failed, schedule retries with increasing delays
                const delays = [300, 1000, 2000, 3000];
                delays.forEach((delay) => {
                    const timer = setTimeout(() => {
                        attemptPlay();
                    }, delay);
                    retryTimers.push(timer);
                });
            });
        }
        
        // Clear retry timers on user interaction
        player.on('click keydown', clearRetryTimers);
        
        // Format time
        function formatTime(seconds) {
            if (isNaN(seconds)) return '0:00';
            const mins = Math.floor(seconds / 60);
            const secs = Math.floor(seconds % 60);
            return mins + ':' + (secs < 10 ? '0' : '') + secs;
        }
        
        // Play/Pause toggle
        playPauseBtn.on('click', function() {
            clearRetryTimers(); // Stop any retry attempts
            if (audio.paused) {
                audio.play();
            } else {
                audio.pause();
            }
        });
        
        // Update play/pause icon
        audio.addEventListener('play', function() {
            iconPlay.hide();
            iconPause.show();
        });
        
        audio.addEventListener('pause', function() {
            iconPlay.show();
            iconPause.hide();
        });
        
        // Previous track
        prevBtn.on('click', function() {
            if (currentTrackIndex > 0) {
                loadTrack(currentTrackIndex - 1);
                tryAutoplayWithRetries();
            }
        });
        
        // Next track
        nextBtn.on('click', function() {
            if (currentTrackIndex < tracks.length - 1) {
                loadTrack(currentTrackIndex + 1);
                tryAutoplayWithRetries();
            }
        });
        
        // Auto-play next track when current ends
        audio.addEventListener('ended', function() {
            if (currentTrackIndex < tracks.length - 1) {
                loadTrack(currentTrackIndex + 1);
                tryAutoplayWithRetries();
            } else {
                iconPlay.show();
                iconPause.hide();
            }
        });
        
        // Update progress bar
        audio.addEventListener('timeupdate', function() {
            if (audio.duration) {
                const progress = (audio.currentTime / audio.duration) * 100;
                progressFill.css('width', progress + '%');
                timeCurrent.text(formatTime(audio.currentTime));
            }
        });
        
        // Update duration
        audio.addEventListener('loadedmetadata', function() {
            timeDuration.text(formatTime(audio.duration));
            
            // Update playlist item duration
            const playlistItem = playlistItems.eq(currentTrackIndex);
            playlistItem.find('.playlist-item-duration').text(formatTime(audio.duration));
        });
        
        // Seek functionality
        progressBar.on('click', function(e) {
            if (!audio.duration) return;
            
            const rect = this.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const percentage = x / rect.width;
            audio.currentTime = percentage * audio.duration;
        });
        
        // Volume control
        volumeControl.on('input', function() {
            audio.volume = $(this).val() / 100;
        });
        
        // Playlist item click
        playlistItems.on('click', function() {
            const index = parseInt($(this).data('index'), 10);
            if (isFinite(index)) {
                loadTrack(index);
                tryAutoplayWithRetries();
            }
        });
        
        // Keyboard shortcuts
        $(document).on('keydown', function(e) {
            // Space bar - play/pause
            if (e.code === 'Space' && $(e.target).is('body')) {
                e.preventDefault();
                playPauseBtn.trigger('click');
            }
            // Arrow left - previous track
            if (e.code === 'ArrowLeft' && e.shiftKey) {
                e.preventDefault();
                prevBtn.trigger('click');
            }
            // Arrow right - next track
            if (e.code === 'ArrowRight' && e.shiftKey) {
                e.preventDefault();
                nextBtn.trigger('click');
            }
        });
        
        // Initialize - load first track
        loadTrack(0);
        
        // Handle autoplay if requested
        if (wantAutoplay) {
            // Try autoplay immediately
            tryAutoplayWithRetries();
            
            // Also try when audio is ready
            audio.addEventListener('canplay', function onCanPlay() {
                audio.removeEventListener('canplay', onCanPlay);
                if (audio.paused) {
                    tryAutoplayWithRetries();
                }
            }, { once: true });
        }
    });
});