/**
 * VMO Voice Selector Component
 * Allows users to choose their preferred OpenAI TTS HD voice
 */

(function($) {
    'use strict';

    window.VMOVoiceSelector = {
        
        /**
         * Initialize voice selector
         */
        init: function() {
            console.log('🎙️ Initializing VMO Voice Selector');
            this.loadVoices();
            this.setupEventListeners();
        },
        
        /**
         * Load available voices from backend
         */
        loadVoices: async function() {
            try {
                const response = await jQuery.ajax({
                    url: vmo_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'vmo_openai_get_voices',
                        nonce: vmo_ajax.nonce
                    }
                });
                
                if (response.success) {
                    this.renderVoiceSelector(response.data.voices, response.data.current);
                } else {
                    console.error('Failed to load voices:', response);
                }
            } catch (error) {
                console.error('Error loading voices:', error);
            }
        },
        
        /**
         * Render voice selector UI
         */
        renderVoiceSelector: function(voices, currentVoice) {
            const container = $('#vmo-voice-selector-container');
            
            if (container.length === 0) {
                console.warn('Voice selector container not found');
                return;
            }
            
            let html = `
                <div class="vmo-voice-selector">
                    <h3>🎙️ Choose Your AI Assistant's Voice</h3>
                    <p>Select the voice you'll hear during your consultation:</p>
                    <div class="vmo-voice-grid">
            `;
            
            for (const [voiceId, voiceData] of Object.entries(voices)) {
                const isSelected = voiceId === currentVoice;
                const icon = voiceData.gender === 'male' ? '👨' : 
                            voiceData.gender === 'female' ? '👩' : '🤖';
                
                html += `
                    <div class="vmo-voice-card ${isSelected ? 'selected' : ''}" data-voice="${voiceId}">
                        <div class="vmo-voice-icon">${icon}</div>
                        <h4>${voiceData.name}</h4>
                        <p>${voiceData.description}</p>
                        <button class="vmo-preview-voice" data-voice="${voiceId}">
                            🔊 Preview
                        </button>
                    </div>
                `;
            }
            
            html += `
                    </div>
                    <div class="vmo-voice-actions">
                        <button id="vmo-save-voice-preference" class="vmo-btn-primary">
                            Continue with Selected Voice
                        </button>
                    </div>
                </div>
            `;
            
            container.html(html);
            
            // Auto-select current voice
            $(`.vmo-voice-card[data-voice="${currentVoice}"]`).addClass('selected');
        },
        
        /**
         * Setup event listeners
         */
        setupEventListeners: function() {
            const self = this;
            
            // Voice card selection
            $(document).on('click', '.vmo-voice-card', function() {
                $('.vmo-voice-card').removeClass('selected');
                $(this).addClass('selected');
            });
            
            // Voice preview
            $(document).on('click', '.vmo-preview-voice', function(e) {
                e.stopPropagation();
                const voice = $(this).data('voice');
                self.previewVoice(voice, $(this));
            });
            
            // Save preference
            $(document).on('click', '#vmo-save-voice-preference', function() {
                self.saveVoicePreference();
            });
        },
        
        /**
         * Preview a voice
         */
        previewVoice: async function(voice, button) {
            const originalText = button.text();
            button.text('⏳ Loading...').prop('disabled', true);
            
            try {
                const response = await jQuery.ajax({
                    url: vmo_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'vmo_openai_preview_voice',
                        nonce: vmo_ajax.nonce,
                        voice: voice
                    }
                });
                
                if (response.success && response.data.audio) {
                    // Convert base64 to blob and play
                    const audioBlob = this.base64ToBlob(response.data.audio, 'audio/mpeg');
                    const audioUrl = URL.createObjectURL(audioBlob);
                    const audio = new Audio(audioUrl);
                    
                    button.text('🔊 Playing...');
                    
                    audio.onended = () => {
                        URL.revokeObjectURL(audioUrl);
                        button.text(originalText).prop('disabled', false);
                    };
                    
                    audio.onerror = () => {
                        URL.revokeObjectURL(audioUrl);
                        button.text(originalText).prop('disabled', false);
                        alert('Failed to play preview');
                    };
                    
                    audio.play();
                } else {
                    throw new Error('Invalid response from server');
                }
            } catch (error) {
                console.error('Preview error:', error);
                button.text(originalText).prop('disabled', false);
                alert('Failed to preview voice');
            }
        },
        
        /**
         * Save voice preference
         */
        saveVoicePreference: async function() {
            const selectedVoice = $('.vmo-voice-card.selected').data('voice');
            
            if (!selectedVoice) {
                alert('Please select a voice');
                return;
            }
            
            const button = $('#vmo-save-voice-preference');
            const originalText = button.text();
            button.text('⏳ Saving...').prop('disabled', true);
            
            try {
                const response = await jQuery.ajax({
                    url: vmo_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'vmo_save_voice_preference',
                        nonce: vmo_ajax.nonce,
                        voice: selectedVoice
                    }
                });
                
                if (response.success) {
                    // Save to localStorage for quick access
                    localStorage.setItem('vmo_preferred_voice', selectedVoice);
                    
                    // Hide selector and trigger callback
                    $('.vmo-voice-selector').fadeOut(300, function() {
                        if (typeof window.vmoVoiceSelected === 'function') {
                            window.vmoVoiceSelected(selectedVoice);
                        }
                    });
                } else {
                    throw new Error(response.data?.message || 'Failed to save preference');
                }
            } catch (error) {
                console.error('Save error:', error);
                button.text(originalText).prop('disabled', false);
                alert('Failed to save voice preference');
            }
        },
        
        /**
         * Convert base64 to Blob
         */
        base64ToBlob: function(base64, contentType) {
            const byteCharacters = atob(base64);
            const byteNumbers = new Array(byteCharacters.length);
            for (let i = 0; i < byteCharacters.length; i++) {
                byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            const byteArray = new Uint8Array(byteNumbers);
            return new Blob([byteArray], { type: contentType });
        },
        
        /**
         * Show voice selector (can be called programmatically)
         */
        show: function(callback) {
            if (callback) {
                window.vmoVoiceSelected = callback;
            }
            
            // If container doesn't exist, create it
            if ($('#vmo-voice-selector-container').length === 0) {
                $('body').append('<div id="vmo-voice-selector-container"></div>');
            }
            
            this.loadVoices();
        },
        
        /**
         * Hide voice selector
         */
        hide: function() {
            $('.vmo-voice-selector').fadeOut();
        }
    };
    
    // Auto-initialize when document ready
    $(document).ready(function() {
        if ($('#vmo-voice-selector-container').length > 0) {
            VMOVoiceSelector.init();
        }
    });
    
})(jQuery);
