/**
 * Pomodoro Timer - Voice Commands & Speech Synthesis
 * 
 * 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: Voice control and text-to-speech functionality
 */

class VoiceController {
    constructor() {
        this.recognition = null;
        this.synthesis = window.speechSynthesis;
        this.isListening = false;
        this.commands = this.initializeCommands();
        this.settings = this.loadSettings();
        this.init();
    }

    init() {
        this.setupSpeechRecognition();
        this.createVoiceInterface();
        this.setupEventListeners();
    }

    initializeCommands() {
        return {
            // Timer commands
            'start timer': () => this.executeCommand('startTimer'),
            'pause timer': () => this.executeCommand('pauseTimer'),
            'stop timer': () => this.executeCommand('stopTimer'),
            'reset timer': () => this.executeCommand('resetTimer'),
            'skip break': () => this.executeCommand('skipBreak'),
            
            // Task commands
            'add task': () => this.executeCommand('addTask'),
            'complete task': () => this.executeCommand('completeTask'),
            'show tasks': () => this.executeCommand('showTasks'),
            
            // Settings commands
            'enable voice': () => this.toggleVoiceControl(true),
            'disable voice': () => this.toggleVoiceControl(false),
            'volume up': () => this.adjustVolume(0.1),
            'volume down': () => this.adjustVolume(-0.1),
            
            // Navigation
            'show statistics': () => this.executeCommand('showStatistics'),
            'open settings': () => this.executeCommand('openSettings'),
            'hide panel': () => this.executeCommand('hidePanel')
        };
    }

    setupSpeechRecognition() {
        if (!('webkitSpeechRecognition' in window || 'SpeechRecognition' in window)) {
            console.warn('Speech recognition not supported');
            return;
        }

        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        this.recognition = new SpeechRecognition();
        this.recognition.continuous = true;
        this.recognition.interimResults = false;
        this.recognition.lang = 'en-US';

        this.recognition.onresult = (event) => {
            const command = event.results[event.results.length - 1][0].transcript.toLowerCase();
            this.processVoiceCommand(command);
        };

        this.recognition.onerror = (event) => {
            console.error('Speech recognition error:', event.error);
            if (event.error === 'not-allowed') {
                this.speak('Microphone access denied. Please allow microphone access to use voice commands.');
            }
        };
    }

    createVoiceInterface() {
        const voiceHTML = `
            <div id="voice-controller" class="voice-controller">
                <div class="voice-header">
                    <h3><i class="fas fa-microphone"></i> Voice Control</h3>
                    <button id="toggle-voice-panel" class="btn-minimize">
                        <i class="fas fa-minus"></i>
                    </button>
                </div>
                
                <div class="voice-content">
                    <div class="voice-status">
                        <div class="status-indicator ${this.isListening ? 'listening' : 'idle'}" id="voice-status">
                            <i class="fas fa-microphone"></i>
                        </div>
                        <span id="voice-status-text">${this.isListening ? 'Listening...' : 'Voice Control Off'}</span>
                    </div>

                    <button id="voice-toggle-btn" class="btn btn-primary voice-btn">
                        <i class="fas fa-microphone"></i>
                        ${this.isListening ? 'Stop Listening' : 'Start Listening'}
                    </button>

                    <div class="voice-commands">
                        <h4>Available Commands:</h4>
                        <ul class="commands-list">
                            <li><strong>"Start timer"</strong> - Begin Pomodoro session</li>
                            <li><strong>"Pause timer"</strong> - Pause current session</li>
                            <li><strong>"Add task"</strong> - Create new task</li>
                            <li><strong>"Complete task"</strong> - Mark task complete</li>
                            <li><strong>"Show statistics"</strong> - View productivity stats</li>
                            <li><strong>"Volume up/down"</strong> - Adjust speech volume</li>
                        </ul>
                    </div>

                    <div class="speech-settings">
                        <div class="setting-item">
                            <label for="speech-rate">Speech Rate:</label>
                            <input type="range" id="speech-rate" min="0.5" max="2" step="0.1" value="1">
                        </div>
                        <div class="setting-item">
                            <label for="speech-pitch">Speech Pitch:</label>
                            <input type="range" id="speech-pitch" min="0.5" max="2" step="0.1" value="1">
                        </div>
                        <div class="setting-item">
                            <label for="speech-volume">Speech Volume:</label>
                            <input type="range" id="speech-volume" min="0" max="1" step="0.1" value="0.8">
                        </div>
                    </div>
                </div>
            </div>
        `;

        const container = document.querySelector('.main-container');
        if (container) {
            container.insertAdjacentHTML('beforeend', voiceHTML);
        }
    }

    setupEventListeners() {
        const toggleBtn = document.getElementById('voice-toggle-btn');
        const minimizeBtn = document.getElementById('toggle-voice-panel');
        const speechRate = document.getElementById('speech-rate');
        const speechPitch = document.getElementById('speech-pitch');
        const speechVolume = document.getElementById('speech-volume');

        if (toggleBtn) {
            toggleBtn.addEventListener('click', () => this.toggleVoiceRecognition());
        }

        if (minimizeBtn) {
            minimizeBtn.addEventListener('click', () => this.toggleVoicePanel());
        }

        if (speechRate) {
            speechRate.addEventListener('input', (e) => {
                this.settings.rate = parseFloat(e.target.value);
                this.saveSettings();
            });
        }

        if (speechPitch) {
            speechPitch.addEventListener('input', (e) => {
                this.settings.pitch = parseFloat(e.target.value);
                this.saveSettings();
            });
        }

        if (speechVolume) {
            speechVolume.addEventListener('input', (e) => {
                this.settings.volume = parseFloat(e.target.value);
                this.saveSettings();
            });
        }
    }

    toggleVoiceRecognition() {
        if (this.isListening) {
            this.stopListening();
        } else {
            this.startListening();
        }
    }

    startListening() {
        if (!this.recognition) {
            this.speak('Speech recognition is not supported in your browser.');
            return;
        }

        this.recognition.start();
        this.isListening = true;
        this.updateVoiceUI();
        this.speak('Voice control activated. I\'m listening for your commands.');
    }

    stopListening() {
        if (this.recognition) {
            this.recognition.stop();
        }
        this.isListening = false;
        this.updateVoiceUI();
    }

    processVoiceCommand(command) {
        console.log('Voice command received:', command);
        
        // Check for command matches
        for (const [phrase, action] of Object.entries(this.commands)) {
            if (command.includes(phrase)) {
                action();
                return;
            }
        }

        // Handle task creation with natural language
        if (command.includes('add task') && command.includes('called')) {
            const taskName = command.split('called')[1]?.trim();
            if (taskName) {
                this.createTaskFromVoice(taskName);
                return;
            }
        }

        // Handle unknown commands
        this.speak('I didn\'t understand that command. Please try again.');
    }

    executeCommand(command) {
        switch (command) {
            case 'startTimer':
                if (window.pomodoroApp && window.pomodoroApp.startTimer) {
                    window.pomodoroApp.startTimer();
                    this.speak('Timer started');
                }
                break;
            case 'pauseTimer':
                if (window.pomodoroApp && window.pomodoroApp.pauseTimer) {
                    window.pomodoroApp.pauseTimer();
                    this.speak('Timer paused');
                }
                break;
            case 'stopTimer':
                if (window.pomodoroApp && window.pomodoroApp.stopTimer) {
                    window.pomodoroApp.stopTimer();
                    this.speak('Timer stopped');
                }
                break;
            case 'resetTimer':
                if (window.pomodoroApp && window.pomodoroApp.resetTimer) {
                    window.pomodoroApp.resetTimer();
                    this.speak('Timer reset');
                }
                break;
            case 'addTask':
                this.speak('Please say the task name after "add task called"');
                break;
            case 'showTasks':
                this.showTasksSummary();
                break;
            case 'showStatistics':
                this.speakStatistics();
                break;
            case 'openSettings':
                this.openSettingsPanel();
                break;
            case 'hidePanel':
                this.hideCurrentPanel();
                break;
        }
    }

    createTaskFromVoice(taskName) {
        if (window.taskManager && window.taskManager.addTask) {
            window.taskManager.addTask({
                title: taskName,
                category: 'Voice Command',
                priority: 'medium',
                estimatedPomodoros: 1
            });
            this.speak(`Task "${taskName}" created successfully`);
        }
    }

    showTasksSummary() {
        const tasks = window.taskManager?.tasks || [];
        const activeTasks = tasks.filter(t => t.status === 'active').length;
        const completedTasks = tasks.filter(t => t.status === 'completed').length;
        
        this.speak(`You have ${activeTasks} active tasks and ${completedTasks} completed tasks`);
    }

    speakStatistics() {
        const sessions = this.getSessionData();
        const todaySessions = sessions.filter(s => {
            const sessionDate = new Date(s.date).toDateString();
            return sessionDate === new Date().toDateString();
        }).length;
        
        this.speak(`Today you completed ${todaySessions} Pomodoro sessions. Keep up the great work!`);
    }

    speak(text) {
        if (!this.synthesis) return;

        const utterance = new SpeechSynthesisUtterance(text);
        utterance.rate = this.settings.rate;
        utterance.pitch = this.settings.pitch;
        utterance.volume = this.settings.volume;
        
        this.synthesis.speak(utterance);
    }

    updateVoiceUI() {
        const statusIndicator = document.getElementById('voice-status');
        const statusText = document.getElementById('voice-status-text');
        const toggleBtn = document.getElementById('voice-toggle-btn');

        if (statusIndicator) {
            statusIndicator.className = `status-indicator ${this.isListening ? 'listening' : 'idle'}`;
        }

        if (statusText) {
            statusText.textContent = this.isListening ? 'Listening...' : 'Voice Control Off';
        }

        if (toggleBtn) {
            toggleBtn.innerHTML = `<i class="fas fa-microphone"></i> ${this.isListening ? 'Stop Listening' : 'Start Listening'}`;
        }
    }

    toggleVoicePanel() {
        const panel = document.getElementById('voice-controller');
        panel.classList.toggle('minimized');
    }

    adjustVolume(delta) {
        this.settings.volume = Math.max(0, Math.min(1, this.settings.volume + delta));
        document.getElementById('speech-volume').value = this.settings.volume;
        this.saveSettings();
        this.speak(`Volume set to ${Math.round(this.settings.volume * 100)} percent`);
    }

    getSessionData() {
        try {
            const sessions = localStorage.getItem('pomodoro_sessions');
            return sessions ? JSON.parse(sessions) : [];
        } catch (error) {
            return [];
        }
    }

    loadSettings() {
        try {
            const saved = localStorage.getItem('pomodoro_voice_settings');
            return saved ? JSON.parse(saved) : {
                rate: 1,
                pitch: 1,
                volume: 0.8,
                enabled: false
            };
        } catch (error) {
            return { rate: 1, pitch: 1, volume: 0.8, enabled: false };
        }
    }

    saveSettings() {
        try {
            localStorage.setItem('pomodoro_voice_settings', JSON.stringify(this.settings));
        } catch (error) {
            console.error('Failed to save voice settings:', error);
        }
    }
}

// Initialize Voice Controller when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    window.voiceController = new VoiceController();
});
