/**
 * Pomodoro Timer - AI Productivity Assistant
 * 
 * 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: AI-powered productivity suggestions and insights
 */

class AIProductivityAssistant {
    constructor() {
        this.userPatterns = this.loadUserPatterns();
        this.suggestions = [];
        this.machineLearningModel = this.initializeMLModel();
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.startPatternAnalysis();
        this.createAIInterface();
    }

    initializeMLModel() {
        // Simple rule-based ML model for productivity insights
        return {
            analyzePatterns: (data) => this.analyzeProductivityPatterns(data),
            predictOptimalBreakTime: (sessions) => this.predictOptimalBreakTime(sessions),
            suggestWorkDuration: (performance) => this.suggestOptimalWorkDuration(performance),
            detectBurnoutRisk: (patterns) => this.detectBurnoutRisk(patterns)
        };
    }

    setupEventListeners() {
        // AI Assistant toggle
        const aiToggle = document.getElementById('ai-assistant-toggle');
        if (aiToggle) {
            aiToggle.addEventListener('click', () => this.toggleAIAssistant());
        }

        // Voice input for AI
        const voiceInputBtn = document.getElementById('ai-voice-input');
        if (voiceInputBtn) {
            voiceInputBtn.addEventListener('click', () => this.startVoiceInput());
        }
    }

    createAIInterface() {
        const aiHTML = `
            <div id="ai-assistant" class="ai-assistant">
                <div class="ai-header">
                    <div class="ai-avatar">
                        <i class="fas fa-robot"></i>
                    </div>
                    <div class="ai-info">
                        <h3>AI Productivity Assistant</h3>
                        <span class="ai-status">Analyzing your patterns...</span>
                    </div>
                    <button id="minimize-ai" class="btn-minimize">
                        <i class="fas fa-minus"></i>
                    </button>
                </div>
                <div class="ai-body">
                    <div class="ai-suggestions" id="ai-suggestions">
                        <!-- AI suggestions will appear here -->
                    </div>
                    <div class="ai-chat">
                        <div class="ai-messages" id="ai-messages">
                            <div class="ai-message ai-welcome">
                                <p>Hello! I'm your AI productivity assistant. I'll analyze your work patterns and provide personalized suggestions to help you be more productive.</p>
                            </div>
                        </div>
                        <div class="ai-input-area">
                            <input type="text" id="ai-input" placeholder="Ask me about productivity...">
                            <button id="ai-send" class="btn btn-primary">
                                <i class="fas fa-paper-plane"></i>
                            </button>
                            <button id="ai-voice-input" class="btn btn-secondary">
                                <i class="fas fa-microphone"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;

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

    setupAIEvents() {
        const sendBtn = document.getElementById('ai-send');
        const aiInput = document.getElementById('ai-input');
        const minimizeBtn = document.getElementById('minimize-ai');

        if (sendBtn) {
            sendBtn.addEventListener('click', () => this.sendAIMessage());
        }

        if (aiInput) {
            aiInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') this.sendAIMessage();
            });
        }

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

    analyzeProductivityPatterns(data) {
        const sessions = data.sessions || [];
        const tasks = data.tasks || [];
        
        const insights = {
            peakProductivityHours: this.findPeakHours(sessions),
            averageSessionLength: this.calculateAverageSessionLength(sessions),
            taskCompletionRate: this.calculateTaskCompletionRate(tasks),
            breakEfficiency: this.analyzeBreakEfficiency(sessions),
            focusTrends: this.analyzeFocusTrends(sessions),
            burnoutIndicators: this.detectBurnoutIndicators(sessions)
        };

        return insights;
    }

    findPeakHours(sessions) {
        const hourCounts = {};
        sessions.forEach(session => {
            const hour = new Date(session.date).getHours();
            hourCounts[hour] = (hourCounts[hour] || 0) + 1;
        });

        const sortedHours = Object.entries(hourCounts)
            .sort(([,a], [,b]) => b - a)
            .slice(0, 3)
            .map(([hour]) => parseInt(hour));

        return sortedHours;
    }

    calculateAverageSessionLength(sessions) {
        if (sessions.length === 0) return 0;
        const totalMinutes = sessions.reduce((sum, session) => sum + (session.duration || 25), 0);
        return Math.round(totalMinutes / sessions.length);
    }

    calculateTaskCompletionRate(tasks) {
        if (tasks.length === 0) return 0;
        const completed = tasks.filter(task => task.status === 'completed').length;
        return Math.round((completed / tasks.length) * 100);
    }

    analyzeBreakEfficiency(sessions) {
        const workSessions = sessions.filter(s => s.type === 'work');
        const breakSessions = sessions.filter(s => s.type === 'break');
        
        if (workSessions.length === 0) return 0;
        
        // Analyze if breaks are helping productivity
        const efficiency = breakSessions.length / workSessions.length;
        return Math.round(efficiency * 100);
    }

    analyzeFocusTrends(sessions) {
        const last7Days = sessions.filter(session => {
            const sessionDate = new Date(session.date);
            const weekAgo = new Date();
            weekAgo.setDate(weekAgo.getDate() - 7);
            return sessionDate >= weekAgo;
        });

        if (last7Days.length < 2) return 'insufficient_data';

        const trend = this.calculateTrend(last7Days.map(s => s.duration || 25));
        return trend > 0 ? 'improving' : trend < 0 ? 'declining' : 'stable';
    }

    detectBurnoutIndicators(sessions) {
        const recentSessions = sessions.filter(session => {
            const sessionDate = new Date(session.date);
            const weekAgo = new Date();
            weekAgo.setDate(weekAgo.getDate() - 7);
            return sessionDate >= weekAgo;
        });

        const indicators = {
            excessiveSessions: recentSessions.length > 40, // More than 40 sessions/week
            decliningPerformance: this.analyzeFocusTrends(recentSessions) === 'declining',
            irregularSchedule: this.hasIrregularSchedule(recentSessions),
            insufficientBreaks: this.hasInsufficientBreaks(recentSessions)
        };

        return Object.values(indicators).filter(Boolean).length;
    }

    calculateTrend(values) {
        if (values.length < 2) return 0;
        const firstHalf = values.slice(0, Math.floor(values.length / 2));
        const secondHalf = values.slice(Math.floor(values.length / 2));
        
        const firstAvg = firstHalf.reduce((a, b) => a + b, 0) / firstHalf.length;
        const secondAvg = secondHalf.reduce((a, b) => a + b, 0) / secondHalf.length;
        
        return secondAvg - firstAvg;
    }

    hasIrregularSchedule(sessions) {
        const hours = sessions.map(s => new Date(s.date).getHours());
        const uniqueHours = new Set(hours).size;
        return uniqueHours > 8; // More than 8 different start hours
    }

    hasInsufficientBreaks(sessions) {
        const workSessions = sessions.filter(s => s.type === 'work');
        const breakSessions = sessions.filter(s => s.type === 'break');
        return workSessions.length > breakSessions.length * 4; // Less than 1 break per 4 work sessions
    }

    generatePersonalizedSuggestions() {
        const data = this.collectUserData();
        const insights = this.machineLearningModel.analyzePatterns(data);
        const suggestions = [];

        // Peak hours suggestion
        if (insights.peakProductivityHours.length > 0) {
            suggestions.push({
                type: 'schedule',
                title: 'Optimal Work Time',
                message: `Your most productive hours are ${insights.peakProductivityHours.map(h => `${h}:00`).join(', ')}. Try scheduling important tasks during these times.`,
                action: 'schedule_tasks',
                priority: 'high'
            });
        }

        // Session length optimization
        if (insights.averageSessionLength > 30) {
            suggestions.push({
                type: 'duration',
                title: 'Session Length Optimization',
                message: 'Your average session length is quite long. Consider shorter, more focused sessions for better productivity.',
                action: 'adjust_timer',
                priority: 'medium'
            });
        }

        // Task completion improvement
        if (insights.taskCompletionRate < 70) {
            suggestions.push({
                type: 'tasks',
                title: 'Task Management',
                message: `Your task completion rate is ${insights.taskCompletionRate}%. Try breaking down larger tasks into smaller, manageable pieces.`,
                action: 'break_down_tasks',
                priority: 'high'
            });
        }

        // Burnout prevention
        if (insights.burnoutIndicators >= 2) {
            suggestions.push({
                type: 'wellness',
                title: 'Burnout Risk Detected',
                message: 'I\'ve noticed some patterns that might lead to burnout. Consider taking more breaks and ensuring adequate rest.',
                action: 'take_break',
                priority: 'urgent'
            });
        }

        // Focus improvement
        if (insights.focusTrends === 'declining') {
            suggestions.push({
                type: 'focus',
                title: 'Focus Improvement',
                message: 'Your focus seems to be declining. Try the Pomodoro technique more strictly or consider a change in environment.',
                action: 'improve_focus',
                priority: 'medium'
            });
        }

        return suggestions;
    }

    collectUserData() {
        return {
            sessions: this.getSessionsData(),
            tasks: this.getTasksData(),
            statistics: this.getStatisticsData(),
            settings: this.getSettingsData()
        };
    }

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

    getTasksData() {
        try {
            const tasks = localStorage.getItem('pomodoro_tasks');
            return tasks ? JSON.parse(tasks) : [];
        } catch (error) {
            return [];
        }
    }

    getStatisticsData() {
        try {
            const stats = localStorage.getItem('pomodoro_statistics');
            return stats ? JSON.parse(stats) : {};
        } catch (error) {
            return {};
        }
    }

    getSettingsData() {
        try {
            const settings = localStorage.getItem('pomodoro_timer_settings');
            return settings ? JSON.parse(settings) : {};
        } catch (error) {
            return {};
        }
    }

    displaySuggestions() {
        const suggestions = this.generatePersonalizedSuggestions();
        const container = document.getElementById('ai-suggestions');
        
        if (!container || suggestions.length === 0) return;

        container.innerHTML = suggestions.map(suggestion => `
            <div class="ai-suggestion ${suggestion.priority}">
                <div class="suggestion-header">
                    <h4>${suggestion.title}</h4>
                    <span class="suggestion-priority ${suggestion.priority}">${suggestion.priority}</span>
                </div>
                <p>${suggestion.message}</p>
                <button class="btn btn-sm btn-primary" data-action="${suggestion.action}">
                    Apply Suggestion
                </button>
            </div>
        `).join('');

        // Add event listeners to suggestion buttons
        container.querySelectorAll('[data-action]').forEach(btn => {
            btn.addEventListener('click', (e) => this.applySuggestion(e.target.dataset.action));
        });
    }

    applySuggestion(action) {
        switch (action) {
            case 'schedule_tasks':
                this.scheduleOptimalTasks();
                break;
            case 'adjust_timer':
                this.adjustTimerSettings();
                break;
            case 'break_down_tasks':
                this.suggestTaskBreakdown();
                break;
            case 'take_break':
                this.suggestBreakTime();
                break;
            case 'improve_focus':
                this.suggestFocusImprovement();
                break;
        }
    }

    scheduleOptimalTasks() {
        const peakHours = this.findPeakHours(this.getSessionsData());
        this.addAIMessage(`I've identified your peak productivity hours as ${peakHours.map(h => `${h}:00`).join(', ')}. Consider scheduling your most important tasks during these times for better results.`);
    }

    adjustTimerSettings() {
        const currentSettings = this.getSettingsData();
        const suggestedDuration = Math.max(15, currentSettings.workDuration - 5);
        this.addAIMessage(`Based on your patterns, I suggest reducing your work sessions to ${suggestedDuration} minutes for better focus and sustainability.`);
    }

    suggestTaskBreakdown() {
        const tasks = this.getTasksData().filter(t => t.status === 'active');
        const largeTasks = tasks.filter(t => (t.estimatedPomodoros || 1) > 4);
        
        if (largeTasks.length > 0) {
            this.addAIMessage(`I found ${largeTasks.length} large tasks that could benefit from being broken down. Consider splitting "${largeTasks[0].title}" into smaller subtasks.`);
        }
    }

    suggestBreakTime() {
        this.addAIMessage('It\'s time for a well-deserved break! Step away from your screen, stretch, or take a short walk. Your future self will thank you.');
    }

    suggestFocusImprovement() {
        this.addAIMessage('To improve your focus, try eliminating distractions, using noise-cancelling headphones, or working in a different environment. Also ensure you\'re getting enough sleep and staying hydrated.');
    }

    sendAIMessage() {
        const input = document.getElementById('ai-input');
        const message = input.value.trim();
        
        if (!message) return;

        this.addUserMessage(message);
        input.value = '';

        // Process the message and generate response
        const response = this.generateAIResponse(message);
        setTimeout(() => this.addAIMessage(response), 500);
    }

    generateAIResponse(message) {
        const lowerMessage = message.toLowerCase();
        
        // Simple rule-based responses
        if (lowerMessage.includes('productivity')) {
            return 'Based on your recent patterns, your productivity peaks during mid-morning. Try scheduling important tasks between 9 AM and 12 PM for best results.';
        } else if (lowerMessage.includes('focus')) {
            return 'To improve focus, ensure you\'re taking regular breaks, staying hydrated, and working in a distraction-free environment. The Pomodoro technique is perfect for this!';
        } else if (lowerMessage.includes('break')) {
            return 'Breaks are essential! I recommend taking a 5-minute break every 25 minutes of work. During breaks, try stretching, walking, or deep breathing exercises.';
        } else if (lowerMessage.includes('task')) {
            return 'For better task management, break down large tasks into smaller, manageable pieces. This makes them less overwhelming and helps you track progress more effectively.';
        } else if (lowerMessage.includes('time')) {
            return 'Time management is about working smarter, not harder. Based on your data, you work most efficiently in focused 25-minute sessions with regular breaks.';
        } else if (lowerMessage.includes('help')) {
            return 'I can help you with productivity tips, focus improvement, task management, break suggestions, and analyzing your work patterns. What would you like to know?';
        } else {
            return 'That\'s an interesting question! Based on your productivity patterns, I suggest focusing on consistent work sessions and regular breaks. Is there something specific about productivity you\'d like to improve?';
        }
    }

    addUserMessage(message) {
        const messagesContainer = document.getElementById('ai-messages');
        const messageHTML = `
            <div class="ai-message user-message">
                <p>${message}</p>
                <span class="message-time">${new Date().toLocaleTimeString()}</span>
            </div>
        `;
        messagesContainer.insertAdjacentHTML('beforeend', messageHTML);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    addAIMessage(message) {
        const messagesContainer = document.getElementById('ai-messages');
        const messageHTML = `
            <div class="ai-message ai-response">
                <p>${message}</p>
                <span class="message-time">${new Date().toLocaleTimeString()}</span>
            </div>
        `;
        messagesContainer.insertAdjacentHTML('beforeend', messageHTML);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    startVoiceInput() {
        if (!('webkitSpeechRecognition' in window || 'SpeechRecognition' in window)) {
            this.addAIMessage('Voice input is not supported in your browser. Please type your message instead.');
            return;
        }

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

        recognition.onstart = () => {
            const voiceInputBtn = document.getElementById('ai-voice-input');
            if (voiceInputBtn) voiceInputBtn.innerHTML = '<i class="fas fa-microphone-slash"></i>';
        };

        recognition.onresult = (event) => {
            const transcript = event.results[0][0].transcript;
            const aiInput = document.getElementById('ai-input');
            if (aiInput) aiInput.value = transcript;
            this.sendAIMessage();
        };

        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.');
            }
        };

        recognition.onend = () => {
            const voiceInputBtn = document.getElementById('ai-voice-input');
            if (voiceInputBtn) voiceInputBtn.innerHTML = '<i class="fas fa-microphone"></i>';
        };

        recognition.start();
    }

    toggleMinimize() {
        const aiAssistant = document.getElementById('ai-assistant');
        if (aiAssistant) aiAssistant.classList.toggle('minimized');
    }

    toggleAIAssistant() {
        const aiAssistant = document.getElementById('ai-assistant');
        if (aiAssistant) aiAssistant.classList.toggle('hidden');
    }

    startPatternAnalysis() {
        // Analyze patterns every 5 minutes
        setInterval(() => {
            this.displaySuggestions();
            this.updateAIStatus();
        }, 5 * 60 * 1000);

        // Initial analysis
        setTimeout(() => {
            this.displaySuggestions();
            this.updateAIStatus();
        }, 2000);
    }

    updateAIStatus() {
        const statusElement = document.querySelector('.ai-status');
        if (statusElement) {
            const insights = this.machineLearningModel.analyzePatterns(this.collectUserData());
            const burnoutRisk = insights.burnoutIndicators >= 2;
            
            statusElement.textContent = burnoutRisk ? '⚠️ Burnout risk detected' : '✅ Analyzing patterns';
            statusElement.className = `ai-status ${burnoutRisk ? 'warning' : 'active'}`;
        }
    }

    loadUserPatterns() {
        try {
            const patterns = localStorage.getItem('pomodoro_user_patterns');
            return patterns ? JSON.parse(patterns) : {};
        } catch (error) {
            return {};
        }
    }

    saveUserPatterns() {
        try {
            localStorage.setItem('pomodoro_user_patterns', JSON.stringify(this.userPatterns));
        } catch (error) {
            console.error('Failed to save user patterns:', error);
        }
    }
}

// Initialize AI Assistant when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    window.aiAssistant = new AIProductivityAssistant();
});
