// Audio Manager for Text-to-Speech functionality
export class AudioManager {
    constructor() {
        this.speechSynthesis = window.speechSynthesis;
        this.voices = [];
        this.currentVoice = null;
        this.isInitialized = false;
        this.init();
    }

    async init() {
        try {
            // Wait for voices to be loaded
            if (this.speechSynthesis.getVoices().length === 0) {
                await new Promise(resolve => {
                    this.speechSynthesis.addEventListener('voiceschanged', resolve, { once: true });
                });
            }

            this.voices = this.speechSynthesis.getVoices();
            this.selectBestVoice();
            this.isInitialized = true;
            
            console.log('🔊 AudioManager initialized with', this.voices.length, 'voices');
        } catch (error) {
            console.error('AudioManager initialization failed:', error);
        }
    }

    selectBestVoice() {
        // Prefer English voices in order of preference
        const preferredVoices = [
            'Google US English',
            'Microsoft Zira - English (United States)',
            'Alex',  // macOS
            'Samantha',  // macOS
            'Google UK English Female',
            'Microsoft Hazel - English (Great Britain)'
        ];

        // Try to find preferred voice
        for (const preferredName of preferredVoices) {
            const voice = this.voices.find(v => v.name.includes(preferredName));
            if (voice) {
                this.currentVoice = voice;
                console.log('🎤 Selected voice:', voice.name);
                return;
            }
        }

        // Fallback to first English voice
        const englishVoice = this.voices.find(voice => 
            voice.lang.startsWith('en')
        );

        if (englishVoice) {
            this.currentVoice = englishVoice;
            console.log('🎤 Using fallback voice:', englishVoice.name);
        } else if (this.voices.length > 0) {
            this.currentVoice = this.voices[0];
            console.log('🎤 Using default voice:', this.voices[0].name);
        }
    }

    async speak(text, options = {}) {
        if (!this.isInitialized) {
            await this.init();
        }

        return new Promise((resolve, reject) => {
            if (!this.speechSynthesis) {
                reject(new Error('Speech synthesis not supported'));
                return;
            }

            // Stop any ongoing speech
            this.speechSynthesis.cancel();

            const utterance = new SpeechSynthesisUtterance(text);
            
            // Configure utterance
            utterance.voice = this.currentVoice;
            utterance.rate = options.rate || 0.9;
            utterance.pitch = options.pitch || 1;
            utterance.volume = options.volume || 1;

            // Event listeners
            utterance.onstart = () => {
                console.log('🔊 Started speaking:', text);
            };

            utterance.onend = () => {
                console.log('✅ Finished speaking:', text);
                resolve();
            };

            utterance.onerror = (event) => {
                console.error('❌ Speech error:', event.error);
                reject(new Error(`Speech synthesis error: ${event.error}`));
            };

            // Start speaking
            this.speechSynthesis.speak(utterance);
        });
    }

    stop() {
        if (this.speechSynthesis) {
            this.speechSynthesis.cancel();
        }
    }

    // Specific method for vocabulary words
    async speakWord(word, options = {}) {
        const wordOptions = {
            rate: 0.8,  // Slower for vocabulary learning
            pitch: 1,
            volume: 1,
            ...options
        };

        try {
            await this.speak(word, wordOptions);
        } catch (error) {
            console.error('Failed to speak word:', word, error);
            // Fallback: show visual feedback
            this.showSpeechFallback(word);
        }
    }

    // Visual fallback when speech fails
    showSpeechFallback(word) {
        // Create temporary visual indicator
        const indicator = document.createElement('div');
        indicator.textContent = `🔊 "${word}"`;
        indicator.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: var(--primary-teal);
            color: white;
            padding: 10px 15px;
            border-radius: 5px;
            font-size: 14px;
            font-weight: 600;
            z-index: 1000;
            animation: fadeInOut 2s ease-in-out;
        `;

        // Add fade animation
        const style = document.createElement('style');
        style.textContent = `
            @keyframes fadeInOut {
                0% { opacity: 0; transform: translateY(-10px); }
                20% { opacity: 1; transform: translateY(0); }
                80% { opacity: 1; transform: translateY(0); }
                100% { opacity: 0; transform: translateY(-10px); }
            }
        `;
        document.head.appendChild(style);
        document.body.appendChild(indicator);

        // Remove after animation
        setTimeout(() => {
            if (indicator.parentNode) {
                indicator.parentNode.removeChild(indicator);
            }
            if (style.parentNode) {
                style.parentNode.removeChild(style);
            }
        }, 2000);
    }

    // Get available voices for user selection
    getAvailableVoices() {
        return this.voices.filter(voice => voice.lang.startsWith('en'));
    }

    // Set custom voice
    setVoice(voiceName) {
        const voice = this.voices.find(v => v.name === voiceName);
        if (voice) {
            this.currentVoice = voice;
            console.log('🎤 Voice changed to:', voice.name);
        }
    }

    // Check if audio is supported
    isSupported() {
        return !!(window.speechSynthesis && window.SpeechSynthesisUtterance);
    }

    // Get current voice info
    getCurrentVoice() {
        return this.currentVoice ? {
            name: this.currentVoice.name,
            lang: this.currentVoice.lang,
            gender: this.currentVoice.name.toLowerCase().includes('female') ? 'female' : 
                   this.currentVoice.name.toLowerCase().includes('male') ? 'male' : 'unknown'
        } : null;
    }
}