/**
 * Pomodoro Timer - Focus Music Integration
 * 
 * Developer: Molla Samser (Founder, RSK World)
 * Designer: Rima Khatun (Designer & Tester, RSK World)
 * Website: https://rskworld.in/
 * Contact: +91 93305 39277 | hello@rskworld.in | support@rskworld.in
 * Location: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India - 713147
 * Year: 2026
 * 
 * Description: Focus music and ambient sound integration for enhanced productivity
 */

class FocusMusicPlayer {
    constructor() {
        this.currentTrack = null;
        this.isPlaying = false;
        this.volume = 0.5;
        this.playlists = this.initializePlaylists();
        this.audioContext = null;
        this.analyser = null;
        this.visualizer = null;
        this.init();
    }

    init() {
        this.setupAudioContext();
        this.createMusicInterface();
        this.setupEventListeners();
        this.loadUserPreferences();
    }

    setupAudioContext() {
        try {
            window.AudioContext = window.AudioContext || window.webkitAudioContext;
            this.audioContext = new AudioContext();
            this.analyser = this.audioContext.createAnalyser();
            this.analyser.fftSize = 256;
        } catch (error) {
            console.error('Web Audio API not supported:', error);
        }
    }

    initializePlaylists() {
        return {
            focus: {
                name: 'Deep Focus',
                description: 'Instrumental music for deep concentration',
                tracks: [
                    {
                        id: 'focus_1',
                        title: 'Alpha Waves',
                        artist: 'RSK World',
                        url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3',
                        duration: 1800,
                        type: 'binaural'
                    },
                    {
                        id: 'focus_2',
                        title: 'Study Flow',
                        artist: 'RSK World',
                        url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3',
                        duration: 2100,
                        type: 'ambient'
                    },
                    {
                        id: 'focus_3',
                        title: 'Concentration Boost',
                        artist: 'RSK World',
                        url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3',
                        duration: 1500,
                        type: 'classical'
                    }
                ]
            },
            nature: {
                name: 'Nature Sounds',
                description: 'Calming natural environments',
                tracks: [
                    {
                        id: 'nature_1',
                        title: 'Rain Sounds',
                        artist: 'Nature',
                        url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-4.mp3',
                        duration: 3600,
                        type: 'rain'
                    },
                    {
                        id: 'nature_2',
                        title: 'Ocean Waves',
                        artist: 'Nature',
                        url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-5.mp3',
                        duration: 3600,
                        type: 'ocean'
                    },
                    {
                        id: 'nature_3',
                        title: 'Forest Ambience',
                        artist: 'Nature',
                        url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-6.mp3',
                        duration: 3600,
                        type: 'forest'
                    }
                ]
            },
            ambient: {
                name: 'Ambient',
                description: 'Atmospheric background music',
                tracks: [
                    {
                        id: 'ambient_1',
                        title: 'Space Journey',
                        artist: 'RSK World',
                        url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-7.mp3',
                        duration: 2400,
                        type: 'space'
                    },
                    {
                        id: 'ambient_2',
                        title: 'Meditation',
                        artist: 'RSK World',
                        url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-8.mp3',
                        duration: 1800,
                        type: 'meditation'
                    }
                ]
            },
            white_noise: {
                name: 'White Noise',
                description: 'Consistent background sounds',
                tracks: [
                    {
                        id: 'white_1',
                        title: 'White Noise',
                        artist: 'Generated',
                        url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-9.mp3',
                        duration: 3600,
                        type: 'white'
                    },
                    {
                        id: 'white_2',
                        title: 'Pink Noise',
                        artist: 'Generated',
                        url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-10.mp3',
                        duration: 3600,
                        type: 'pink'
                    }
                ]
            }
        };
    }

    createMusicInterface() {
        const musicHTML = `
            <div id="focus-music-player" class="focus-music-player">
                <div class="player-header">
                    <h3><i class="fas fa-music"></i> Focus Music</h3>
                    <button id="toggle-music-player" class="btn-minimize">
                        <i class="fas fa-minus"></i>
                    </button>
                </div>
                
                <div class="player-content">
                    <div class="playlist-selector">
                        <select id="playlist-select" class="playlist-select">
                            ${Object.entries(this.playlists).map(([key, playlist]) => 
                                `<option value="${key}">${playlist.name}</option>`
                            ).join('')}
                        </select>
                    </div>

                    <div class="track-list" id="track-list">
                        <!-- Tracks will be populated here -->
                    </div>

                    <div class="now-playing" id="now-playing">
                        <div class="track-info">
                            <h4 id="track-title">Select a track</h4>
                            <p id="track-artist">No track playing</p>
                        </div>
                        <div class="track-progress">
                            <div class="progress-bar">
                                <div class="progress-fill" id="music-progress"></div>
                            </div>
                            <div class="time-display">
                                <span id="current-time">0:00</span>
                                <span id="total-time">0:00</span>
                            </div>
                        </div>
                    </div>

                    <div class="player-controls">
                        <button id="prev-track" class="btn btn-secondary">
                            <i class="fas fa-step-backward"></i>
                        </button>
                        <button id="play-pause" class="btn btn-primary">
                            <i class="fas fa-play"></i>
                        </button>
                        <button id="next-track" class="btn btn-secondary">
                            <i class="fas fa-step-forward"></i>
                        </button>
                        <button id="repeat-track" class="btn btn-secondary">
                            <i class="fas fa-redo"></i>
                        </button>
                    </div>

                    <div class="volume-control">
                        <i class="fas fa-volume-down"></i>
                        <input type="range" id="volume-slider" min="0" max="100" value="50">
                        <i class="fas fa-volume-up"></i>
                        <span id="volume-display">50%</span>
                    </div>

                    <div class="visualizer-container">
                        <canvas id="music-visualizer" width="300" height="100"></canvas>
                    </div>

                    <div class="music-settings">
                        <label class="checkbox-label">
                            <input type="checkbox" id="auto-play">
                            <span>Auto-play during work sessions</span>
                        </label>
                        <label class="checkbox-label">
                            <input type="checkbox" id="fade-in-out">
                            <span>Fade in/out</span>
                        </label>
                        <label class="checkbox-label">
                            <input type="checkbox" id="crossfade">
                            <span>Crossfade between tracks</span>
                        </label>
                    </div>
                </div>
            </div>
        `;

        const container = document.querySelector('.main-container');
        if (container) {
            container.insertAdjacentHTML('beforeend', musicHTML);
            this.populateTrackList();
            this.setupVisualizer();
        }
    }

    setupEventListeners() {
        // Playlist selector
        const playlistSelect = document.getElementById('playlist-select');
        if (playlistSelect) {
            playlistSelect.addEventListener('change', (e) => {
                this.selectPlaylist(e.target.value);
            });
        }

        // Player controls
        const playPauseBtn = document.getElementById('play-pause');
        const prevBtn = document.getElementById('prev-track');
        const nextBtn = document.getElementById('next-track');
        const repeatBtn = document.getElementById('repeat-track');

        if (playPauseBtn) playPauseBtn.addEventListener('click', () => this.togglePlayPause());
        if (prevBtn) prevBtn.addEventListener('click', () => this.playPreviousTrack());
        if (nextBtn) nextBtn.addEventListener('click', () => this.playNextTrack());
        if (repeatBtn) repeatBtn.addEventListener('click', () => this.toggleRepeat());

        // Volume control
        const volumeSlider = document.getElementById('volume-slider');
        if (volumeSlider) {
            volumeSlider.addEventListener('input', (e) => {
                this.setVolume(e.target.value / 100);
            });
        }

        // Toggle player
        const toggleBtn = document.getElementById('toggle-music-player');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', () => this.togglePlayer());
        }

        // Settings
        const autoPlayCheckbox = document.getElementById('auto-play');
        const fadeCheckbox = document.getElementById('fade-in-out');
        const crossfadeCheckbox = document.getElementById('crossfade');

        if (autoPlayCheckbox) {
            autoPlayCheckbox.addEventListener('change', (e) => {
                this.settings.autoPlay = e.target.checked;
                this.saveUserPreferences();
            });
        }

        if (fadeCheckbox) {
            fadeCheckbox.addEventListener('change', (e) => {
                this.settings.fadeInOut = e.target.checked;
                this.saveUserPreferences();
            });
        }

        if (crossfadeCheckbox) {
            crossfadeCheckbox.addEventListener('change', (e) => {
                this.settings.crossfade = e.target.checked;
                this.saveUserPreferences();
            });
        }
    }

    populateTrackList() {
        const trackList = document.getElementById('track-list');
        const selectedPlaylist = document.getElementById('playlist-select').value;
        const playlist = this.playlists[selectedPlaylist];

        if (!trackList || !playlist) return;

        trackList.innerHTML = playlist.tracks.map(track => `
            <div class="track-item" data-track-id="${track.id}">
                <div class="track-info">
                    <h4>${track.title}</h4>
                    <p>${track.artist} • ${this.formatDuration(track.duration)}</p>
                </div>
                <button class="btn btn-sm btn-primary play-track" data-track-id="${track.id}">
                    <i class="fas fa-play"></i>
                </button>
            </div>
        `).join('');

        // Add click listeners to track items
        trackList.querySelectorAll('.play-track').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const trackId = e.currentTarget.dataset.trackId;
                this.playTrack(trackId);
            });
        });
    }

    selectPlaylist(playlistKey) {
        this.currentPlaylist = playlistKey;
        this.populateTrackList();
    }

    playTrack(trackId) {
        const selectedPlaylist = document.getElementById('playlist-select').value;
        const playlist = this.playlists[selectedPlaylist];
        const track = playlist.tracks.find(t => t.id === trackId);

        if (!track) return;

        // Stop current track if playing
        if (this.currentAudio) {
            this.currentAudio.pause();
            this.currentAudio = null;
        }

        // Create new audio element
        this.currentAudio = new Audio(track.url);
        this.currentTrack = track;

        // Setup audio events
        this.currentAudio.addEventListener('loadedmetadata', () => {
            this.updateTrackInfo(track);
            this.updateTimeDisplay();
        });

        this.currentAudio.addEventListener('timeupdate', () => {
            this.updateProgress();
            this.updateVisualizer();
        });

        this.currentAudio.addEventListener('ended', () => {
            this.handleTrackEnd();
        });

        // Connect to analyser if available
        if (this.audioContext && this.analyser) {
            const source = this.audioContext.createMediaElementSource(this.currentAudio);
            source.connect(this.analyser);
            this.analyser.connect(this.audioContext.destination);
        }

        // Apply fade in if enabled
        if (this.settings.fadeInOut) {
            this.fadeIn();
        }

        this.currentAudio.play();
        this.isPlaying = true;
        this.updatePlayButton();
        this.updateTrackHighlight(trackId);
    }

    togglePlayPause() {
        if (!this.currentAudio) {
            // Play first track of current playlist
            const selectedPlaylist = document.getElementById('playlist-select').value;
            const playlist = this.playlists[selectedPlaylist];
            if (playlist.tracks.length > 0) {
                this.playTrack(playlist.tracks[0].id);
            }
            return;
        }

        if (this.isPlaying) {
            this.currentAudio.pause();
            this.isPlaying = false;
        } else {
            this.currentAudio.play();
            this.isPlaying = true;
        }

        this.updatePlayButton();
    }

    playNextTrack() {
        const selectedPlaylist = document.getElementById('playlist-select').value;
        const playlist = this.playlists[selectedPlaylist];
        
        if (!this.currentTrack || !playlist) return;

        const currentIndex = playlist.tracks.findIndex(t => t.id === this.currentTrack.id);
        const nextIndex = (currentIndex + 1) % playlist.tracks.length;
        
        this.playTrack(playlist.tracks[nextIndex].id);
    }

    playPreviousTrack() {
        const selectedPlaylist = document.getElementById('playlist-select').value;
        const playlist = this.playlists[selectedPlaylist];
        
        if (!this.currentTrack || !playlist) return;

        const currentIndex = playlist.tracks.findIndex(t => t.id === this.currentTrack.id);
        const prevIndex = currentIndex === 0 ? playlist.tracks.length - 1 : currentIndex - 1;
        
        this.playTrack(playlist.tracks[prevIndex].id);
    }

    toggleRepeat() {
        this.settings.repeat = !this.settings.repeat;
        const repeatBtn = document.getElementById('repeat-track');
        repeatBtn.classList.toggle('active', this.settings.repeat);
        this.saveUserPreferences();
    }

    setVolume(volume) {
        this.volume = volume;
        if (this.currentAudio) {
            this.currentAudio.volume = volume;
        }
        
        const volumeDisplay = document.getElementById('volume-display');
        if (volumeDisplay) {
            volumeDisplay.textContent = `${Math.round(volume * 100)}%`;
        }
    }

    updateTrackInfo(track) {
        const titleElement = document.getElementById('track-title');
        const artistElement = document.getElementById('track-artist');
        
        if (titleElement) titleElement.textContent = track.title;
        if (artistElement) artistElement.textContent = track.artist;
    }

    updateProgress() {
        if (!this.currentAudio) return;

        const progress = (this.currentAudio.currentTime / this.currentAudio.duration) * 100;
        const progressBar = document.getElementById('music-progress');
        
        if (progressBar) {
            progressBar.style.width = `${progress}%`;
        }

        this.updateTimeDisplay();
    }

    updateTimeDisplay() {
        if (!this.currentAudio) return;

        const currentTimeElement = document.getElementById('current-time');
        const totalTimeElement = document.getElementById('total-time');
        
        if (currentTimeElement) {
            currentTimeElement.textContent = this.formatTime(this.currentAudio.currentTime);
        }
        
        if (totalTimeElement) {
            totalTimeElement.textContent = this.formatTime(this.currentAudio.duration);
        }
    }

    updatePlayButton() {
        const playPauseBtn = document.getElementById('play-pause');
        if (playPauseBtn) {
            const icon = playPauseBtn.querySelector('i');
            icon.className = this.isPlaying ? 'fas fa-pause' : 'fas fa-play';
        }
    }

    updateTrackHighlight(trackId) {
        document.querySelectorAll('.track-item').forEach(item => {
            item.classList.toggle('playing', item.dataset.trackId === trackId);
        });
    }

    handleTrackEnd() {
        if (this.settings.repeat) {
            this.currentAudio.currentTime = 0;
            this.currentAudio.play();
        } else {
            this.playNextTrack();
        }
    }

    fadeIn() {
        if (!this.currentAudio) return;
        
        this.currentAudio.volume = 0;
        const targetVolume = this.volume;
        const fadeStep = targetVolume / 50; // 50 steps for smooth fade
        
        const fadeInterval = setInterval(() => {
            if (this.currentAudio.volume < targetVolume) {
                this.currentAudio.volume = Math.min(targetVolume, this.currentAudio.volume + fadeStep);
            } else {
                clearInterval(fadeInterval);
            }
        }, 50);
    }

    fadeOut(callback) {
        if (!this.currentAudio) return;
        
        const fadeStep = this.currentAudio.volume / 50;
        
        const fadeInterval = setInterval(() => {
            if (this.currentAudio.volume > 0) {
                this.currentAudio.volume = Math.max(0, this.currentAudio.volume - fadeStep);
            } else {
                clearInterval(fadeInterval);
                if (callback) callback();
            }
        }, 50);
    }

    setupVisualizer() {
        const canvas = document.getElementById('music-visualizer');
        if (!canvas || !this.analyser) return;

        const ctx = canvas.getContext('2d');
        const bufferLength = this.analyser.frequencyBinCount;
        const dataArray = new Uint8Array(bufferLength);

        const draw = () => {
            requestAnimationFrame(draw);
            
            this.analyser.getByteFrequencyData(dataArray);
            
            ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            const barWidth = (canvas.width / bufferLength) * 2.5;
            let barHeight;
            let x = 0;
            
            for (let i = 0; i < bufferLength; i++) {
                barHeight = (dataArray[i] / 255) * canvas.height;
                
                const r = barHeight + 25 * (i / bufferLength);
                const g = 250 * (i / bufferLength);
                const b = 50;
                
                ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;
                ctx.fillRect(x, canvas.height - barHeight, barWidth, barHeight);
                
                x += barWidth + 1;
            }
        };

        draw();
    }

    updateVisualizer() {
        // Visualizer is updated in the draw loop
    }

    togglePlayer() {
        const player = document.getElementById('focus-music-player');
        player.classList.toggle('minimized');
    }

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

    formatDuration(seconds) {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        
        if (hours > 0) {
            return `${hours}h ${minutes}m`;
        } else {
            return `${minutes}m`;
        }
    }

    loadUserPreferences() {
        try {
            const saved = localStorage.getItem('pomodoro_music_settings');
            this.settings = saved ? JSON.parse(saved) : {
                autoPlay: false,
                fadeInOut: true,
                crossfade: false,
                repeat: false,
                volume: 0.5,
                lastPlaylist: 'focus'
            };
            
            // Apply saved settings
            this.setVolume(this.settings.volume);
            document.getElementById('volume-slider').value = this.settings.volume * 100;
            document.getElementById('playlist-select').value = this.settings.lastPlaylist;
            
            if (this.settings.repeat) {
                document.getElementById('repeat-track').classList.add('active');
            }
            
            document.getElementById('auto-play').checked = this.settings.autoPlay;
            document.getElementById('fade-in-out').checked = this.settings.fadeInOut;
            document.getElementById('crossfade').checked = this.settings.crossfade;
            
        } catch (error) {
            this.settings = {
                autoPlay: false,
                fadeInOut: true,
                crossfade: false,
                repeat: false,
                volume: 0.5,
                lastPlaylist: 'focus'
            };
        }
    }

    saveUserPreferences() {
        try {
            this.settings.lastPlaylist = document.getElementById('playlist-select').value;
            localStorage.setItem('pomodoro_music_settings', JSON.stringify(this.settings));
        } catch (error) {
            console.error('Failed to save music settings:', error);
        }
    }

    // Integration with Pomodoro timer
    autoPlayForWorkSession() {
        if (this.settings.autoPlay && !this.isPlaying) {
            this.togglePlayPause();
        }
    }

    pauseForBreakSession() {
        if (this.isPlaying && this.settings.autoPlay) {
            this.togglePlayPause();
        }
    }
}

// Initialize Focus Music Player when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    window.focusMusicPlayer = new FocusMusicPlayer();
});
