/**
 * Pomodoro Timer - Advanced Analytics Dashboard
 * 
 * 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: Advanced analytics and insights dashboard
 */

class AdvancedAnalytics {
    constructor() {
        this.data = this.collectAllData();
        this.charts = {};
        this.insights = [];
        this.init();
    }

    init() {
        this.createAnalyticsInterface();
        this.setupEventListeners();
        this.generateInsights();
        this.renderCharts();
    }

    collectAllData() {
        return {
            sessions: this.getSessionsData(),
            tasks: this.getTasksData(),
            settings: this.getSettingsData(),
            userProfile: this.getUserProfile()
        };
    }

    createAnalyticsInterface() {
        const analyticsHTML = `
            <div id="advanced-analytics" class="advanced-analytics">
                <div class="analytics-header">
                    <h2><i class="fas fa-chart-line"></i> Advanced Analytics</h2>
                    <div class="analytics-controls">
                        <select id="analytics-period" class="period-selector">
                            <option value="7">Last 7 Days</option>
                            <option value="30">Last 30 Days</option>
                            <option value="90">Last 3 Months</option>
                            <option value="365">Last Year</option>
                            <option value="all">All Time</option>
                        </select>
                        <button id="export-analytics" class="btn btn-secondary">
                            <i class="fas fa-download"></i> Export
                        </button>
                    </div>
                </div>

                <div class="analytics-summary">
                    <div class="summary-cards">
                        <div class="summary-card">
                            <div class="card-icon">
                                <i class="fas fa-clock"></i>
                            </div>
                            <div class="card-content">
                                <h3>Total Focus Time</h3>
                                <span class="card-value" id="total-focus-time">0h 0m</span>
                                <span class="card-change positive" id="focus-time-change">+0%</span>
                            </div>
                        </div>
                        <div class="summary-card">
                            <div class="card-icon">
                                <i class="fas fa-fire"></i>
                            </div>
                            <div class="card-content">
                                <h3>Current Streak</h3>
                                <span class="card-value" id="current-streak">0 days</span>
                                <span class="card-change" id="streak-change">Personal best: 0</span>
                            </div>
                        </div>
                        <div class="summary-card">
                            <div class="card-icon">
                                <i class="fas fa-tasks"></i>
                            </div>
                            <div class="card-content">
                                <h3>Tasks Completed</h3>
                                <span class="card-value" id="tasks-completed">0</span>
                                <span class="card-change positive" id="tasks-change">+0%</span>
                            </div>
                        </div>
                        <div class="summary-card">
                            <div class="card-icon">
                                <i class="fas fa-chart-bar"></i>
                            </div>
                            <div class="card-content">
                                <h3>Productivity Score</h3>
                                <span class="card-value" id="productivity-score">0</span>
                                <span class="card-change positive" id="score-change">+0</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="analytics-charts">
                    <div class="chart-container">
                        <h3>Productivity Trends</h3>
                        <canvas id="productivity-chart"></canvas>
                    </div>
                    <div class="chart-container">
                        <h3>Session Distribution</h3>
                        <canvas id="session-distribution-chart"></canvas>
                    </div>
                    <div class="chart-container">
                        <h3>Hourly Focus Pattern</h3>
                        <canvas id="hourly-pattern-chart"></canvas>
                    </div>
                    <div class="chart-container">
                        <h3>Task Categories</h3>
                        <canvas id="task-categories-chart"></canvas>
                    </div>
                </div>

                <div class="analytics-insights">
                    <h3><i class="fas fa-lightbulb"></i> AI-Powered Insights</h3>
                    <div class="insights-grid" id="insights-grid">
                        <!-- Insights will be populated here -->
                    </div>
                </div>

                <div class="analytics-details">
                    <div class="detail-section">
                        <h3>Peak Performance Hours</h3>
                        <div class="performance-hours" id="performance-hours">
                            <!-- Performance hours will be populated here -->
                        </div>
                    </div>
                    <div class="detail-section">
                        <h3>Productivity Patterns</h3>
                        <div class="patterns-list" id="patterns-list">
                            <!-- Patterns will be populated here -->
                        </div>
                    </div>
                    <div class="detail-section">
                        <h3>Recommendations</h3>
                        <div class="recommendations-list" id="recommendations-list">
                            <!-- Recommendations will be populated here -->
                        </div>
                    </div>
                </div>
            </div>
        `;

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

    setupEventListeners() {
        const periodSelector = document.getElementById('analytics-period');
        const exportBtn = document.getElementById('export-analytics');

        if (periodSelector) {
            periodSelector.addEventListener('change', () => {
                this.updateAnalytics();
            });
        }

        if (exportBtn) {
            exportBtn.addEventListener('click', () => {
                this.exportAnalyticsData();
            });
        }
    }

    generateInsights() {
        const sessions = this.data.sessions;
        const tasks = this.data.tasks;
        const periodElement = document.getElementById('analytics-period');
        const period = periodElement ? parseInt(periodElement.value) : 7; // Default to 7 days
        const filteredSessions = this.filterDataByPeriod(sessions, period);

        this.insights = [
            this.analyzeProductivityTrend(filteredSessions),
            this.analyzeOptimalWorkTime(filteredSessions),
            this.analyzeTaskEfficiency(tasks),
            this.analyzeBreakPatterns(filteredSessions),
            this.analyzeConsistency(filteredSessions),
            this.analyzeDistractionFactors(filteredSessions)
        ];
    }

    analyzeProductivityTrend(sessions) {
        if (sessions.length < 2) {
            return {
                type: 'info',
                title: 'Insufficient Data',
                message: 'Complete more sessions to see productivity trends.',
                action: 'Continue working'
            };
        }

        const recentSessions = sessions.slice(-7);
        const olderSessions = sessions.slice(-14, -7);
        
        const recentAvg = recentSessions.length;
        const olderAvg = olderSessions.length || 1;
        
        const trend = ((recentAvg - olderAvg) / olderAvg) * 100;
        
        return {
            type: trend > 0 ? 'positive' : trend < 0 ? 'negative' : 'neutral',
            title: 'Productivity Trend',
            message: `Your productivity has ${trend > 0 ? 'increased' : trend < 0 ? 'decreased' : 'remained stable'} by ${Math.abs(trend).toFixed(1)}% this week.`,
            action: trend > 0 ? 'Keep it up!' : 'Try adjusting your schedule'
        };
    }

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

        const peakHour = Object.entries(hourCounts)
            .sort(([,a], [,b]) => b - a)[0];

        if (!peakHour) {
            return {
                type: 'info',
                title: 'Work Schedule',
                message: 'No clear pattern detected yet.',
                action: 'Maintain consistent schedule'
            };
        }

        return {
            type: 'positive',
            title: 'Peak Performance Time',
            message: `You work most efficiently around ${peakHour[0]}:00. Schedule important tasks during this time.`,
            action: 'Optimize your schedule'
        };
    }

    analyzeTaskEfficiency(tasks) {
        const completedTasks = tasks.filter(t => t.status === 'completed');
        if (completedTasks.length === 0) {
            return {
                type: 'info',
                title: 'Task Management',
                message: 'Start completing tasks to see efficiency insights.',
                action: 'Focus on task completion'
            };
        }

        const avgPomodoros = completedTasks.reduce((sum, task) => 
            sum + (task.completedPomodoros || 0), 0) / completedTasks.length;

        return {
            type: avgPomodoros <= 2 ? 'positive' : 'neutral',
            title: 'Task Efficiency',
            message: `You complete tasks in an average of ${avgPomodoros.toFixed(1)} Pomodoro sessions.`,
            action: avgPomodoros > 2 ? 'Consider breaking down large tasks' : 'Great efficiency!'
        };
    }

    analyzeBreakPatterns(sessions) {
        const workSessions = sessions.filter(s => s.type === 'work');
        const breakSessions = sessions.filter(s => s.type === 'break');
        
        if (workSessions.length === 0) {
            return {
                type: 'info',
                title: 'Break Analysis',
                message: 'No break patterns detected yet.',
                action: 'Take regular breaks'
            };
        }

        const breakRatio = breakSessions.length / workSessions.length;
        const optimalRatio = 0.25; // 1 break per 4 work sessions
        
        return {
            type: Math.abs(breakRatio - optimalRatio) < 0.1 ? 'positive' : 'neutral',
            title: 'Break Balance',
            message: `Your break ratio is ${(breakRatio * 100).toFixed(0)}%. ${breakRatio < optimalRatio ? 'Take more breaks' : breakRatio > optimalRatio ? 'Good balance' : 'Perfect balance!'}`,
            action: breakRatio < optimalRatio ? 'Take more breaks' : 'Maintain this balance'
        };
    }

    analyzeConsistency(sessions) {
        const dailySessions = {};
        sessions.forEach(session => {
            const day = new Date(session.date).toDateString();
            dailySessions[day] = (dailySessions[day] || 0) + 1;
        });

        const days = Object.keys(dailySessions);
        if (days.length < 7) {
            return {
                type: 'info',
                title: 'Consistency',
                message: 'Build a daily routine for better consistency.',
                action: 'Create a daily schedule'
            };
        }

        const variance = this.calculateVariance(Object.values(dailySessions));
        const consistency = variance < 2 ? 'high' : variance < 4 ? 'medium' : 'low';

        return {
            type: consistency === 'high' ? 'positive' : consistency === 'medium' ? 'neutral' : 'negative',
            title: 'Work Consistency',
            message: `Your work consistency is ${consistency}. ${consistency === 'high' ? 'Excellent routine!' : consistency === 'medium' ? 'Good progress!' : 'Try to maintain a more regular schedule.'}`,
            action: consistency === 'low' ? 'Establish daily routine' : 'Keep it consistent'
        };
    }

    analyzeDistractionFactors(sessions) {
        const incompleteSessions = sessions.filter(s => !s.completed);
        if (incompleteSessions.length === 0) {
            return {
                type: 'positive',
                title: 'Focus Quality',
                message: 'Excellent focus! All sessions completed.',
                action: 'Maintain this focus'
            };
        }

        const distractionRate = (incompleteSessions.length / sessions.length) * 100;
        
        return {
            type: distractionRate < 10 ? 'positive' : distractionRate < 25 ? 'neutral' : 'negative',
            title: 'Focus Analysis',
            message: `${distractionRate.toFixed(0)}% of sessions were interrupted. ${distractionRate > 25 ? 'Consider minimizing distractions.' : 'Good focus level!'}`,
            action: distractionRate > 25 ? 'Minimize distractions' : 'Maintain focus environment'
        };
    }

    calculateVariance(values) {
        const mean = values.reduce((a, b) => a + b, 0) / values.length;
        const squaredDiffs = values.map(value => Math.pow(value - mean, 2));
        return squaredDiffs.reduce((a, b) => a + b, 0) / values.length;
    }

    renderCharts() {
        this.renderProductivityChart();
        this.renderSessionDistributionChart();
        this.renderHourlyPatternChart();
        this.renderTaskCategoriesChart();
    }

    renderProductivityChart() {
        const ctx = document.getElementById('productivity-chart');
        if (!ctx) return;

        const periodElement = document.getElementById('analytics-period');
        const period = periodElement ? parseInt(periodElement.value) : 7;
        const filteredSessions = this.filterDataByPeriod(this.data.sessions, period);
        
        const dailyData = this.aggregateDailyData(filteredSessions);
        
        if (this.charts.productivity) {
            this.charts.productivity.destroy();
        }

        this.charts.productivity = new Chart(ctx, {
            type: 'line',
            data: {
                labels: dailyData.map(d => d.date),
                datasets: [{
                    label: 'Sessions Completed',
                    data: dailyData.map(d => d.sessions),
                    borderColor: '#FF6B6B',
                    backgroundColor: 'rgba(255, 107, 107, 0.1)',
                    tension: 0.4
                }, {
                    label: 'Focus Minutes',
                    data: dailyData.map(d => d.focusMinutes),
                    borderColor: '#4ECDC4',
                    backgroundColor: 'rgba(78, 205, 196, 0.1)',
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'top'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }

    renderSessionDistributionChart() {
        const ctx = document.getElementById('session-distribution-chart');
        if (!ctx) return;

        const sessionTypes = this.aggregateSessionTypes(this.data.sessions);
        
        if (this.charts.distribution) {
            this.charts.distribution.destroy();
        }

        this.charts.distribution = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: Object.keys(sessionTypes),
                datasets: [{
                    data: Object.values(sessionTypes),
                    backgroundColor: ['#FF6B6B', '#4ECDC4', '#FFD93D', '#6BCF7F']
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    }

    renderHourlyPatternChart() {
        const ctx = document.getElementById('hourly-pattern-chart');
        if (!ctx) return;

        const hourlyData = this.aggregateHourlyData(this.data.sessions);
        
        if (this.charts.hourly) {
            this.charts.hourly.destroy();
        }

        this.charts.hourly = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: hourlyData.map(d => `${d.hour}:00`),
                datasets: [{
                    label: 'Sessions',
                    data: hourlyData.map(d => d.sessions),
                    backgroundColor: '#FF6B6B'
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }

    renderTaskCategoriesChart() {
        const ctx = document.getElementById('task-categories-chart');
        if (!ctx) return;

        const categories = this.aggregateTaskCategories(this.data.tasks);
        
        if (this.charts.categories) {
            this.charts.categories.destroy();
        }

        this.charts.categories = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: Object.keys(categories),
                datasets: [{
                    label: 'Tasks',
                    data: Object.values(categories),
                    backgroundColor: '#4ECDC4'
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }

    aggregateDailyData(sessions) {
        const dailyMap = {};
        
        sessions.forEach(session => {
            const date = new Date(session.date).toLocaleDateString();
            if (!dailyMap[date]) {
                dailyMap[date] = { date, sessions: 0, focusMinutes: 0 };
            }
            dailyMap[date].sessions++;
            dailyMap[date].focusMinutes += session.duration || 25;
        });

        return Object.values(dailyMap).slice(-30); // Last 30 days
    }

    aggregateSessionTypes(sessions) {
        const types = {};
        sessions.forEach(session => {
            types[session.type] = (types[session.type] || 0) + 1;
        });
        return types;
    }

    aggregateHourlyData(sessions) {
        const hourly = {};
        for (let i = 0; i < 24; i++) {
            hourly[i] = { hour: i, sessions: 0 };
        }

        sessions.forEach(session => {
            const hour = new Date(session.date).getHours();
            hourly[hour].sessions++;
        });

        return Object.values(hourly);
    }

    aggregateTaskCategories(tasks) {
        const categories = {};
        tasks.forEach(task => {
            categories[task.category] = (categories[task.category] || 0) + 1;
        });
        return categories;
    }

    updateAnalytics() {
        this.data = this.collectAllData();
        this.generateInsights();
        this.renderCharts();
        this.updateSummaryCards();
        this.updateInsightsDisplay();
    }

    updateSummaryCards() {
        const periodElement = document.getElementById('analytics-period');
        const period = periodElement ? parseInt(periodElement.value) : 7;
        const filteredSessions = this.filterDataByPeriod(this.data.sessions, period);
        const filteredTasks = this.filterDataByPeriod(this.data.tasks, period);

        // Update focus time
        const totalMinutes = filteredSessions.reduce((sum, s) => sum + (s.duration || 25), 0);
        const hours = Math.floor(totalMinutes / 60);
        const minutes = totalMinutes % 60;
        const focusTimeElement = document.getElementById('total-focus-time');
        if (focusTimeElement) focusTimeElement.textContent = `${hours}h ${minutes}m`;

        // Update streak
        const streak = this.calculateCurrentStreak(filteredSessions);
        const streakElement = document.getElementById('current-streak');
        if (streakElement) streakElement.textContent = `${streak} days`;

        // Update tasks completed
        const completedTasks = filteredTasks.filter(t => t.status === 'completed').length;
        const tasksElement = document.getElementById('tasks-completed');
        if (tasksElement) tasksElement.textContent = completedTasks;

        // Update productivity score
        const score = this.calculateProductivityScore(filteredSessions, filteredTasks);
        const scoreElement = document.getElementById('productivity-score');
        if (scoreElement) scoreElement.textContent = score;
    }

    updateInsightsDisplay() {
        const container = document.getElementById('insights-grid');
        if (!container) return;

        container.innerHTML = this.insights.map(insight => `
            <div class="insight-card ${insight.type}">
                <div class="insight-icon">
                    <i class="fas fa-${this.getInsightIcon(insight.type)}"></i>
                </div>
                <div class="insight-content">
                    <h4>${insight.title}</h4>
                    <p>${insight.message}</p>
                    <span class="insight-action">${insight.action}</span>
                </div>
            </div>
        `).join('');
    }

    getInsightIcon(type) {
        const icons = {
            positive: 'check-circle',
            negative: 'exclamation-triangle',
            neutral: 'info-circle',
            info: 'lightbulb'
        };
        return icons[type] || 'info-circle';
    }

    filterDataByPeriod(data, days) {
        if (days === 'all') return data;
        
        const cutoffDate = new Date();
        cutoffDate.setDate(cutoffDate.getDate() - days);
        
        return data.filter(item => {
            const itemDate = new Date(item.date || item.createdAt);
            return itemDate >= cutoffDate;
        });
    }

    calculateCurrentStreak(sessions) {
        const sessionDates = [...new Set(sessions.map(s => new Date(s.date).toDateString()))];
        
        if (sessionDates.length === 0) return 0;
        
        let streak = 0;
        let checkDate = new Date();
        
        while (sessionDates.includes(checkDate.toDateString())) {
            streak++;
            checkDate.setDate(checkDate.getDate() - 1);
        }
        
        return streak;
    }

    calculateProductivityScore(sessions, tasks) {
        const sessionScore = Math.min(100, sessions.length * 2);
        const taskScore = Math.min(100, tasks.filter(t => t.status === 'completed').length * 5);
        const streakScore = Math.min(100, this.calculateCurrentStreak(sessions) * 10);
        
        return Math.round((sessionScore + taskScore + streakScore) / 3);
    }

    exportAnalyticsData() {
        const exportData = {
            summary: {
                totalSessions: this.data.sessions.length,
                totalTasks: this.data.tasks.length,
                productivityScore: this.calculateProductivityScore(this.data.sessions, this.data.tasks),
                currentStreak: this.calculateCurrentStreak(this.data.sessions)
            },
            insights: this.insights,
            charts: {
                dailyData: this.aggregateDailyData(this.data.sessions),
                sessionTypes: this.aggregateSessionTypes(this.data.sessions),
                hourlyData: this.aggregateHourlyData(this.data.sessions),
                taskCategories: this.aggregateTaskCategories(this.data.tasks)
            },
            exportDate: new Date().toISOString()
        };

        const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `pomodoro-analytics-${new Date().toISOString().split('T')[0]}.json`;
        a.click();
        URL.revokeObjectURL(url);
    }

    // Data getters
    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 [];
        }
    }

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

    getUserProfile() {
        try {
            const profile = localStorage.getItem('pomodoro_user_profile');
            return profile ? JSON.parse(profile) : {};
        } catch (error) {
            return {};
        }
    }
}

// Initialize Advanced Analytics when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    window.advancedAnalytics = new AdvancedAnalytics();
});
