/**
 * Pomodoro Timer - Gamification System
 * 
 * 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: Gamification system with achievements, rewards, and progress tracking
 */

class GamificationSystem {
    constructor() {
        this.userProfile = this.loadUserProfile();
        this.achievements = this.initializeAchievements();
        this.rewards = this.initializeRewards();
        this.leaderboard = this.loadLeaderboard();
        this.streaks = this.calculateStreaks();
        this.init();
    }

    init() {
        this.createGamificationInterface();
        this.setupEventListeners();
        this.updateUI();
        this.checkForAchievements();
    }

    initializeAchievements() {
        return {
            // Session-based achievements
            first_session: {
                id: 'first_session',
                title: 'First Steps',
                description: 'Complete your first Pomodoro session',
                icon: '🎯',
                points: 10,
                category: 'sessions',
                unlocked: false
            },
            session_warrior: {
                id: 'session_warrior',
                title: 'Session Warrior',
                description: 'Complete 10 Pomodoro sessions',
                icon: '⚔️',
                points: 50,
                category: 'sessions',
                unlocked: false
            },
            marathon_runner: {
                id: 'marathon_runner',
                title: 'Marathon Runner',
                description: 'Complete 50 Pomodoro sessions',
                icon: '🏃',
                points: 200,
                category: 'sessions',
                unlocked: false
            },
            centurion: {
                id: 'centurion',
                title: 'Centurion',
                description: 'Complete 100 Pomodoro sessions',
                icon: '💯',
                points: 500,
                category: 'sessions',
                unlocked: false
            },

            // Streak-based achievements
            streak_starter: {
                id: 'streak_starter',
                title: 'Streak Starter',
                description: 'Maintain a 3-day streak',
                icon: '🔥',
                points: 30,
                category: 'streaks',
                unlocked: false
            },
            week_warrior: {
                id: 'week_warrior',
                title: 'Week Warrior',
                description: 'Maintain a 7-day streak',
                icon: '📅',
                points: 100,
                category: 'streaks',
                unlocked: false
            },
            month_master: {
                id: 'month_master',
                title: 'Month Master',
                description: 'Maintain a 30-day streak',
                icon: '🗓️',
                points: 500,
                category: 'streaks',
                unlocked: false
            },

            // Time-based achievements
            early_bird: {
                id: 'early_bird',
                title: 'Early Bird',
                description: 'Complete 5 sessions before 9 AM',
                icon: '🌅',
                points: 75,
                category: 'time',
                unlocked: false
            },
            night_owl: {
                id: 'night_owl',
                title: 'Night Owl',
                description: 'Complete 5 sessions after 9 PM',
                icon: '🦉',
                points: 75,
                category: 'time',
                unlocked: false
            },
            weekend_warrior: {
                id: 'weekend_warrior',
                title: 'Weekend Warrior',
                description: 'Complete 10 sessions on weekends',
                icon: '🎉',
                points: 100,
                category: 'time',
                unlocked: false
            },

            // Task-based achievements
            task_master: {
                id: 'task_master',
                title: 'Task Master',
                description: 'Complete 10 tasks',
                icon: '✅',
                points: 150,
                category: 'tasks',
                unlocked: false
            },
            productivity_guru: {
                id: 'productivity_guru',
                title: 'Productivity Guru',
                description: 'Complete 25 tasks',
                icon: '🧘',
                points: 300,
                category: 'tasks',
                unlocked: false
            },

            // Special achievements
            perfectionist: {
                id: 'perfectionist',
                title: 'Perfectionist',
                description: 'Complete 10 sessions without skipping breaks',
                icon: '💎',
                points: 250,
                category: 'special',
                unlocked: false
            },
            focus_master: {
                id: 'focus_master',
                title: 'Focus Master',
                description: 'Complete a 2-hour focused work session',
                icon: '🧠',
                points: 200,
                category: 'special',
                unlocked: false
            },
            social_butterfly: {
                id: 'social_butterfly',
                title: 'Social Butterfly',
                description: 'Share your progress 5 times',
                icon: '🦋',
                points: 50,
                category: 'social',
                unlocked: false
            }
        };
    }

    initializeRewards() {
        return {
            // Themes
            golden_theme: {
                id: 'golden_theme',
                title: 'Golden Theme',
                description: 'Unlock premium golden theme',
                cost: 500,
                type: 'theme',
                unlocked: false,
                data: {
                    primaryColor: '#FFD700',
                    accentColor: '#FFA500',
                    backgroundColor: '#FFFACD',
                    textColor: '#2C2C2C'
                }
            },
            neon_theme: {
                id: 'neon_theme',
                title: 'Neon Theme',
                description: 'Unlock futuristic neon theme',
                cost: 750,
                type: 'theme',
                unlocked: false,
                data: {
                    primaryColor: '#FF00FF',
                    accentColor: '#00FFFF',
                    backgroundColor: '#0A0A0A',
                    textColor: '#FFFFFF'
                }
            },

            // Badges
            elite_badge: {
                id: 'elite_badge',
                title: 'Elite User Badge',
                description: 'Display elite status on your profile',
                cost: 1000,
                type: 'badge',
                unlocked: false
            },
            veteran_badge: {
                id: 'veteran_badge',
                title: 'Veteran Badge',
                description: 'Show your veteran status',
                cost: 2000,
                type: 'badge',
                unlocked: false
            },

            // Power-ups
            double_points: {
                id: 'double_points',
                title: 'Double Points (24h)',
                description: 'Earn double points for 24 hours',
                cost: 300,
                type: 'powerup',
                unlocked: false,
                duration: 86400000 // 24 hours in milliseconds
            },
            instant_focus: {
                id: 'instant_focus',
                title: 'Instant Focus',
                description: 'Skip break timer once',
                cost: 100,
                type: 'powerup',
                unlocked: false
            }
        };
    }

    createGamificationInterface() {
        const gamificationHTML = `
            <div id="gamification-panel" class="gamification-panel">
                <div class="panel-header">
                    <h2><i class="fas fa-trophy"></i> Achievements & Rewards</h2>
                    <div class="user-level">
                        <span class="level-badge">Level ${this.userProfile.level}</span>
                        <div class="exp-bar">
                            <div class="exp-fill" style="width: ${(this.userProfile.experience / this.getExpForNextLevel()) * 100}%"></div>
                        </div>
                        <span class="exp-text">${this.userProfile.experience}/${this.getExpForNextLevel()} XP</span>
                    </div>
                </div>

                <div class="panel-tabs">
                    <button class="tab-btn active" data-tab="achievements">Achievements</button>
                    <button class="tab-btn" data-tab="rewards">Rewards Store</button>
                    <button class="tab-btn" data-tab="leaderboard">Leaderboard</button>
                    <button class="tab-btn" data-tab="profile">Profile</button>
                </div>

                <div class="tab-content">
                    <!-- Achievements Tab -->
                    <div id="achievements-tab" class="tab-pane active">
                        <div class="achievements-grid" id="achievements-grid">
                            <!-- Achievements will be populated here -->
                        </div>
                    </div>

                    <!-- Rewards Tab -->
                    <div id="rewards-tab" class="tab-pane">
                        <div class="rewards-header">
                            <div class="user-points">
                                <i class="fas fa-coins"></i>
                                <span id="user-points">${this.userProfile.points}</span> Points
                            </div>
                        </div>
                        <div class="rewards-grid" id="rewards-grid">
                            <!-- Rewards will be populated here -->
                        </div>
                    </div>

                    <!-- Leaderboard Tab -->
                    <div id="leaderboard-tab" class="tab-pane">
                        <div class="leaderboard-container">
                            <div class="leaderboard-filters">
                                <select id="leaderboard-period">
                                    <option value="daily">Daily</option>
                                    <option value="weekly">Weekly</option>
                                    <option value="monthly">Monthly</option>
                                    <option value="all-time">All Time</option>
                                </select>
                            </div>
                            <div class="leaderboard-list" id="leaderboard-list">
                                <!-- Leaderboard will be populated here -->
                            </div>
                        </div>
                    </div>

                    <!-- Profile Tab -->
                    <div id="profile-tab" class="tab-pane">
                        <div class="profile-container">
                            <div class="profile-header">
                                <div class="profile-avatar">
                                    <i class="fas fa-user"></i>
                                    <div class="level-indicator">${this.userProfile.level}</div>
                                </div>
                                <div class="profile-info">
                                    <h3>Productivity Champion</h3>
                                    <p>Member since ${new Date(this.userProfile.joinDate).toLocaleDateString()}</p>
                                </div>
                            </div>
                            
                            <div class="profile-stats">
                                <div class="stat-item">
                                    <span class="stat-value">${this.userProfile.totalSessions}</span>
                                    <span class="stat-label">Total Sessions</span>
                                </div>
                                <div class="stat-item">
                                    <span class="stat-value">${this.userProfile.currentStreak}</span>
                                    <span class="stat-label">Current Streak</span>
                                </div>
                                <div class="stat-item">
                                    <span class="stat-value">${this.userProfile.longestStreak}</span>
                                    <span class="stat-label">Longest Streak</span>
                                </div>
                                <div class="stat-item">
                                    <span class="stat-value">${this.userProfile.tasksCompleted}</span>
                                    <span class="stat-label">Tasks Completed</span>
                                </div>
                            </div>

                            <div class="profile-badges">
                                <h4>Unlocked Badges</h4>
                                <div class="badges-collection" id="user-badges">
                                    <!-- Badges will be populated here -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;

        const container = document.querySelector('.main-container');
        if (container) {
            container.insertAdjacentHTML('beforeend', gamificationHTML);
            this.populateAchievements();
            this.populateRewards();
            this.populateLeaderboard();
            this.populateProfile();
        }
    }

    setupEventListeners() {
        // Tab switching
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                this.switchTab(e.target.dataset.tab);
            });
        });

        // Leaderboard period filter
        const periodSelect = document.getElementById('leaderboard-period');
        if (periodSelect) {
            periodSelect.addEventListener('change', () => {
                this.populateLeaderboard();
            });
        }

        // Reward purchase buttons
        document.addEventListener('click', (e) => {
            if (e.target.matches('.buy-reward')) {
                this.purchaseReward(e.target.dataset.rewardId);
            }
        });
    }

    switchTab(tabName) {
        // Update tab buttons
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.toggle('active', btn.dataset.tab === tabName);
        });

        // Update tab content
        document.querySelectorAll('.tab-pane').forEach(pane => {
            pane.classList.toggle('active', pane.id === `${tabName}-tab`);
        });
    }

    populateAchievements() {
        const grid = document.getElementById('achievements-grid');
        if (!grid) return;

        const categories = {
            sessions: 'Sessions',
            streaks: 'Streaks',
            time: 'Time-based',
            tasks: 'Tasks',
            special: 'Special',
            social: 'Social'
        };

        let html = '';
        Object.entries(categories).forEach(([category, title]) => {
            const categoryAchievements = Object.values(this.achievements).filter(a => a.category === category);
            
            html += `
                <div class="achievement-category">
                    <h3>${title}</h3>
                    <div class="category-achievements">
                        ${categoryAchievements.map(achievement => this.createAchievementCard(achievement)).join('')}
                    </div>
                </div>
            `;
        });

        grid.innerHTML = html;
    }

    createAchievementCard(achievement) {
        const unlocked = this.userProfile.achievements.includes(achievement.id);
        const progress = this.getAchievementProgress(achievement);
        
        return `
            <div class="achievement-card ${unlocked ? 'unlocked' : 'locked'}">
                <div class="achievement-icon">${achievement.icon}</div>
                <div class="achievement-info">
                    <h4>${achievement.title}</h4>
                    <p>${achievement.description}</p>
                    <div class="achievement-progress">
                        <div class="progress-bar">
                            <div class="progress-fill" style="width: ${progress}%"></div>
                        </div>
                        <span class="progress-text">${progress}%</span>
                    </div>
                    <div class="achievement-points">
                        <i class="fas fa-star"></i> ${achievement.points} points
                    </div>
                </div>
            </div>
        `;
    }

    populateRewards() {
        const grid = document.getElementById('rewards-grid');
        if (!grid) return;

        const categories = {
            theme: 'Themes',
            badge: 'Badges',
            powerup: 'Power-ups'
        };

        let html = '';
        Object.entries(categories).forEach(([category, title]) => {
            const categoryRewards = Object.values(this.rewards).filter(r => r.type === category);
            
            html += `
                <div class="reward-category">
                    <h3>${title}</h3>
                    <div class="category-rewards">
                        ${categoryRewards.map(reward => this.createRewardCard(reward)).join('')}
                    </div>
                </div>
            `;
        });

        grid.innerHTML = html;
    }

    createRewardCard(reward) {
        const unlocked = this.userProfile.rewards.includes(reward.id);
        const canAfford = this.userProfile.points >= reward.cost;
        
        return `
            <div class="reward-card ${unlocked ? 'unlocked' : ''} ${!canAfford ? 'cant-afford' : ''}">
                <div class="reward-icon">
                    <i class="fas fa-${this.getRewardIcon(reward.type)}"></i>
                </div>
                <div class="reward-info">
                    <h4>${reward.title}</h4>
                    <p>${reward.description}</p>
                    <div class="reward-cost">
                        <i class="fas fa-coins"></i> ${reward.cost} points
                    </div>
                </div>
                <div class="reward-action">
                    ${unlocked ? 
                        '<span class="owned">Owned</span>' : 
                        `<button class="btn btn-primary buy-reward" data-reward-id="${reward.id}" ${!canAfford ? 'disabled' : ''}>
                            ${canAfford ? 'Buy' : 'Insufficient Points'}
                        </button>`
                    }
                </div>
            </div>
        `;
    }

    getRewardIcon(type) {
        const icons = {
            theme: 'palette',
            badge: 'certificate',
            powerup: 'bolt'
        };
        return icons[type] || 'gift';
    }

    populateLeaderboard() {
        const list = document.getElementById('leaderboard-list');
        const period = document.getElementById('leaderboard-period').value;
        
        if (!list) return;

        const filteredLeaderboard = this.filterLeaderboardByPeriod(period);
        
        list.innerHTML = filteredLeaderboard.map((user, index) => `
            <div class="leaderboard-item ${index < 3 ? 'top-' + (index + 1) : ''}">
                <div class="rank">${index + 1}</div>
                <div class="user-info">
                    <div class="user-avatar">
                        <i class="fas fa-user"></i>
                    </div>
                    <div class="user-details">
                        <h4>${user.name}</h4>
                        <span class="user-level">Level ${user.level}</span>
                    </div>
                </div>
                <div class="user-score">
                    <span class="score">${user.score}</span>
                    <span class="score-label">points</span>
                </div>
            </div>
        `).join('');
    }

    populateProfile() {
        const badgesContainer = document.getElementById('user-badges');
        if (!badgesContainer) return;

        const userBadges = this.userProfile.rewards.filter(id => 
            this.rewards[id] && this.rewards[id].type === 'badge'
        );

        badgesContainer.innerHTML = userBadges.length > 0 ? 
            userBadges.map(badgeId => {
                const badge = this.rewards[badgeId];
                return `<div class="badge-item" title="${badge.title}"><i class="fas fa-${this.getRewardIcon(badge.type)}"></i></div>`;
            }).join('') :
            '<p>No badges unlocked yet. Keep working!</p>';
    }

    getAchievementProgress(achievement) {
        const sessions = this.getSessionsData();
        const tasks = this.getTasksData();
        
        switch (achievement.id) {
            case 'first_session':
                return sessions.length > 0 ? 100 : 0;
            case 'session_warrior':
                return Math.min(100, (sessions.length / 10) * 100);
            case 'marathon_runner':
                return Math.min(100, (sessions.length / 50) * 100);
            case 'centurion':
                return Math.min(100, (sessions.length / 100) * 100);
            case 'streak_starter':
                return Math.min(100, (this.userProfile.currentStreak / 3) * 100);
            case 'week_warrior':
                return Math.min(100, (this.userProfile.currentStreak / 7) * 100);
            case 'month_master':
                return Math.min(100, (this.userProfile.currentStreak / 30) * 100);
            case 'task_master':
                return Math.min(100, (tasks.filter(t => t.status === 'completed').length / 10) * 100);
            case 'productivity_guru':
                return Math.min(100, (tasks.filter(t => t.status === 'completed').length / 25) * 100);
            default:
                return 0;
        }
    }

    checkForAchievements() {
        Object.values(this.achievements).forEach(achievement => {
            if (!this.userProfile.achievements.includes(achievement.id)) {
                const progress = this.getAchievementProgress(achievement);
                if (progress >= 100) {
                    this.unlockAchievement(achievement);
                }
            }
        });
    }

    unlockAchievement(achievement) {
        this.userProfile.achievements.push(achievement.id);
        this.userProfile.points += achievement.points;
        this.userProfile.experience += achievement.points;
        
        this.checkLevelUp();
        this.saveUserProfile();
        this.updateUI();
        
        this.showAchievementNotification(achievement);
    }

    showAchievementNotification(achievement) {
        const notification = document.createElement('div');
        notification.className = 'achievement-notification';
        notification.innerHTML = `
            <div class="achievement-popup">
                <div class="achievement-icon">${achievement.icon}</div>
                <div class="achievement-details">
                    <h4>Achievement Unlocked!</h4>
                    <p>${achievement.title}</p>
                    <span class="points-earned">+${achievement.points} points</span>
                </div>
            </div>
        `;
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.classList.add('show');
        }, 100);
        
        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 3000);
    }

    purchaseReward(rewardId) {
        const reward = this.rewards[rewardId];
        if (!reward || this.userProfile.points < reward.cost) return;

        this.userProfile.points -= reward.cost;
        this.userProfile.rewards.push(rewardId);
        
        if (reward.type === 'theme') {
            this.applyTheme(reward.data);
        } else if (reward.type === 'powerup') {
            this.activatePowerUp(reward);
        }
        
        this.saveUserProfile();
        this.updateUI();
        this.populateRewards();
        
        if (window.pomodoroApp && window.pomodoroApp.showNotification) {
            window.pomodoroApp.showNotification(`Purchased ${reward.title}!`, 'success');
        }
    }

    applyTheme(themeData) {
        if (window.themeManager) {
            window.themeManager.applyCustomTheme(themeData);
        }
    }

    activatePowerUp(powerUp) {
        // Handle power-up activation
        if (powerUp.id === 'double_points') {
            this.userProfile.activePowerUps.push({
                id: powerUp.id,
                expires: Date.now() + powerUp.duration
            });
        }
    }

    checkLevelUp() {
        const nextLevelExp = this.getExpForNextLevel();
        if (this.userProfile.experience >= nextLevelExp) {
            this.userProfile.experience -= nextLevelExp;
            this.userProfile.level++;
            this.showLevelUpNotification();
        }
    }

    showLevelUpNotification() {
        if (window.pomodoroApp && window.pomodoroApp.showNotification) {
            window.pomodoroApp.showNotification(`Level Up! You're now level ${this.userProfile.level}!`, 'success');
        }
    }

    getExpForNextLevel() {
        return this.userProfile.level * 100;
    }

    updateUI() {
        // Update level and experience
        const levelBadge = document.querySelector('.level-badge');
        const expFill = document.querySelector('.exp-fill');
        const expText = document.querySelector('.exp-text');
        const userPoints = document.getElementById('user-points');
        
        if (levelBadge) levelBadge.textContent = `Level ${this.userProfile.level}`;
        if (expFill) expFill.style.width = `${(this.userProfile.experience / this.getExpForNextLevel()) * 100}%`;
        if (expText) expText.textContent = `${this.userProfile.experience}/${this.getExpForNextLevel()} XP`;
        if (userPoints) userPoints.textContent = this.userProfile.points;
    }

    // Session tracking
    trackSession(sessionData) {
        this.userProfile.totalSessions++;
        this.updateStreaks();
        this.addPoints(10); // Base points for session
        this.checkForAchievements();
        this.saveUserProfile();
        this.updateUI();
    }

    addPoints(points) {
        const multiplier = this.hasActivePowerUp('double_points') ? 2 : 1;
        this.userProfile.points += points * multiplier;
        this.userProfile.experience += points * multiplier;
    }

    hasActivePowerUp(powerUpId) {
        return this.userProfile.activePowerUps.some(powerUp => 
            powerUp.id === powerUpId && powerUp.expires > Date.now()
        );
    }

    updateStreaks() {
        const today = new Date().toDateString();
        const lastSession = this.userProfile.lastSessionDate;
        
        if (lastSession === today) {
            // Same day, don't update streak
            return;
        }
        
        const yesterday = new Date();
        yesterday.setDate(yesterday.getDate() - 1);
        
        if (lastSession === yesterday.toDateString()) {
            // Consecutive day
            this.userProfile.currentStreak++;
        } else {
            // Streak broken
            this.userProfile.currentStreak = 1;
        }
        
        this.userProfile.lastSessionDate = today;
        this.userProfile.longestStreak = Math.max(this.userProfile.longestStreak, this.userProfile.currentStreak);
    }

    calculateStreaks() {
        // Calculate streaks from session data
        const sessions = this.getSessionsData();
        const sessionDates = [...new Set(sessions.map(s => new Date(s.date).toDateString()))];
        
        let currentStreak = 0;
        let longestStreak = 0;
        let tempStreak = 0;
        
        const today = new Date().toDateString();
        const yesterday = new Date();
        yesterday.setDate(yesterday.getDate() - 1);
        
        // Check if there's a session today or yesterday
        if (sessionDates.includes(today) || sessionDates.includes(yesterday.toDateString())) {
            // Calculate current streak
            let checkDate = new Date();
            while (sessionDates.includes(checkDate.toDateString())) {
                currentStreak++;
                checkDate.setDate(checkDate.getDate() - 1);
            }
        }
        
        // Calculate longest streak
        sessionDates.forEach((date, index) => {
            if (index === 0) {
                tempStreak = 1;
            } else {
                const prevDate = new Date(sessionDates[index - 1]);
                const currDate = new Date(date);
                const diffDays = Math.floor((currDate - prevDate) / (1000 * 60 * 60 * 24));
                
                if (diffDays === 1) {
                    tempStreak++;
                } else {
                    longestStreak = Math.max(longestStreak, tempStreak);
                    tempStreak = 1;
                }
            }
        });
        
        longestStreak = Math.max(longestStreak, tempStreak);
        
        return { currentStreak, longestStreak };
    }

    // Data management
    loadUserProfile() {
        try {
            const saved = localStorage.getItem('pomodoro_user_profile');
            if (saved) {
                return JSON.parse(saved);
            }
        } catch (error) {
            console.error('Failed to load user profile:', error);
        }
        
        return {
            level: 1,
            experience: 0,
            points: 0,
            totalSessions: 0,
            currentStreak: 0,
            longestStreak: 0,
            tasksCompleted: 0,
            achievements: [],
            rewards: [],
            activePowerUps: [],
            joinDate: Date.now(),
            lastSessionDate: null
        };
    }

    saveUserProfile() {
        try {
            localStorage.setItem('pomodoro_user_profile', JSON.stringify(this.userProfile));
        } catch (error) {
            console.error('Failed to save user profile:', error);
        }
    }

    loadLeaderboard() {
        try {
            const saved = localStorage.getItem('pomodoro_leaderboard');
            return saved ? JSON.parse(saved) : this.generateMockLeaderboard();
        } catch (error) {
            return this.generateMockLeaderboard();
        }
    }

    generateMockLeaderboard() {
        const names = ['Alex Chen', 'Sarah Johnson', 'Mike Williams', 'Emma Davis', 'James Brown', 'Lisa Anderson', 'David Miller', 'Anna Taylor'];
        return names.map((name, index) => ({
            name: name,
            level: Math.floor(Math.random() * 20) + 1,
            score: Math.floor(Math.random() * 5000) + 1000
        })).sort((a, b) => b.score - a.score);
    }

    filterLeaderboardByPeriod(period) {
        // In a real implementation, this would filter by actual time periods
        // For now, return the same data with some variation
        const leaderboard = [...this.leaderboard];
        
        if (period === 'daily') {
            return leaderboard.slice(0, 5).map(user => ({
                ...user,
                score: Math.floor(user.score * 0.1)
            }));
        } else if (period === 'weekly') {
            return leaderboard.slice(0, 8).map(user => ({
                ...user,
                score: Math.floor(user.score * 0.5)
            }));
        } else if (period === 'monthly') {
            return leaderboard.slice(0, 10).map(user => ({
                ...user,
                score: Math.floor(user.score * 0.8)
            }));
        }
        
        return leaderboard;
    }

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

// Initialize Gamification System when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    window.gamificationSystem = new GamificationSystem();
});
