/**
 * KAASAEGNE MOTIVATSIOONIMOODULI JAVASCRIPT - PARANDATUD
 * Chart.js konfliktid lahendatud + showChart meetod lisatud
 */

class ModernMotivationModule {
    constructor() {
        this.achievements = new Map();
        this.challenges = new Map();
        this.currentView = 'progression';
        this.charts = {}; // 🚨 LISATUD: Chart storage
        this.animations = {
            enabled: !window.matchMedia('(prefers-reduced-motion: reduce)').matches
        };
        
        this.colors = {
            primary: '#374151',
            secondary: '#6b7280',
            accent: '#d1d5db',
            background: '#f9fafb',
            white: '#ffffff'
        };
        
        this.init();
    }
    
    init() {
        console.log('📊 Kaasaegne motivatsioonimoodul laetud');
        
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.initializeComponents());
        } else {
            this.initializeComponents();
        }
    }
    
    initializeComponents() {
        this.initializeAchievements();
        this.initializeChallenges();
        this.initializeProgressBars();
        this.initializeInteractions();
        this.initializeChartNavigation();
        this.initializeCharts(); // 🚨 LISATUD: Charts initialization
        
        // 🚨 LISATUD: Handle pending chart request
        if (window.pendingChartRequest) {
            this.showChart(window.pendingChartRequest);
            window.pendingChartRequest = null;
        }
        
        console.log('✅ Kõik komponendid aktiveeritud');
    }
    
    /**
     * 🚨 LISATUD: CHART.JS SÜSTEEM
     */
    initializeCharts() {
        // Kontrolli kas Chart.js on laetud
        if (typeof Chart === 'undefined') {
            console.error('❌ Chart.js pole laetud');
            return;
        }
        
        console.log('📊 Initializing charts system');
        this.createAllCharts();
        this.showChart('progression'); // Nüüd see töötab!
        console.log('✅ Charts ready');
    }
    
    createAllCharts() {
        this.createProgressionChart();
        this.createMonthlyChart();
        this.createAchievementsChart();
    }
    
    /**
     * 🚨 PARANDATUD: Chart creation with proper cleanup
     */
    createProgressionChart() {
        const ctx = document.getElementById('progressionChart');
        if (!ctx) {
            console.warn('progressionChart canvas not found');
            return;
        }
        
        // 🚨 KRIITILISELT PARANDATUD: Hävita olemasolev chart
        const existingChart = Chart.getChart(ctx);
        if (existingChart) {
            existingChart.destroy();
        }
        
        // Get data from global variables set by PHP
        const progressionData = window.progressionData || [];
        
        const labels = [];
        const dataPoints = [];
        const maxPoints = [];
        
        if (progressionData.length > 0) {
            progressionData.forEach(item => {
                labels.push(this.formatMonth(item.month));
                dataPoints.push(parseFloat(item.avg_points) || 0);
                maxPoints.push(parseFloat(item.max_points) || 0);
            });
        } else {
            // Fallback data
            labels.push('Juuni 2025');
            dataPoints.push(11.0);
            maxPoints.push(12.5);
        }
        
        this.charts.progression = new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: 'Keskmine punktid',
                    data: dataPoints,
                    borderColor: this.colors.primary,
                    backgroundColor: this.colors.accent + '30',
                    borderWidth: 3,
                    fill: true,
                    tension: 0.4,
                    pointBackgroundColor: this.colors.primary,
                    pointBorderColor: '#ffffff',
                    pointBorderWidth: 2,
                    pointRadius: 6
                }, {
                    label: 'Parim tulemus',
                    data: maxPoints,
                    borderColor: this.colors.secondary,
                    backgroundColor: 'transparent',
                    borderWidth: 2,
                    borderDash: [5, 5],
                    fill: false,
                    pointBackgroundColor: this.colors.secondary,
                    pointBorderColor: '#ffffff',
                    pointBorderWidth: 2,
                    pointRadius: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    intersect: false,
                    mode: 'index'
                },
                plugins: {
                    legend: {
                        display: true,
                        position: 'bottom',
                        labels: {
                            boxWidth: 12,
                            padding: 20,
                            color: this.colors.secondary
                        }
                    },
                    tooltip: {
                        backgroundColor: 'rgba(255, 255, 255, 0.95)',
                        titleColor: this.colors.primary,
                        bodyColor: this.colors.secondary,
                        borderColor: this.colors.accent,
                        borderWidth: 1
                    }
                },
                scales: {
                    x: {
                        grid: {
                            color: this.colors.accent + '50'
                        },
                        ticks: {
                            color: this.colors.secondary
                        }
                    },
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: this.colors.accent + '50'
                        },
                        ticks: {
                            color: this.colors.secondary
                        },
                        title: {
                            display: true,
                            text: 'Punktid',
                            color: this.colors.secondary
                        }
                    }
                }
            }
        });
    }
    
    createMonthlyChart() {
        const ctx = document.getElementById('monthlyChart');
        if (!ctx) {
            console.warn('monthlyChart canvas not found');
            return;
        }
        
        // 🚨 KRIITILISELT PARANDATUD: Hävita olemasolev chart
        const existingChart = Chart.getChart(ctx);
        if (existingChart) {
            existingChart.destroy();
        }
        
        const monthlyData = window.monthlyStats || [];
        const labels = [];
        const dataPoints = [];
        const months = ['Jan', 'Veeb', 'Märts', 'Apr', 'Mai', 'Juuni', 'Juuli', 'Aug', 'Sept', 'Okt', 'Nov', 'Dets'];
        
        if (monthlyData.length > 0) {
            monthlyData.forEach(item => {
                const monthIndex = parseInt(item.month) - 1;
                labels.push(months[monthIndex]);
                dataPoints.push(parseFloat(item.avg_points) || 0);
            });
        } else {
            labels.push('Juuni');
            dataPoints.push(11.0);
        }
        
        this.charts.monthly = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: 'Keskmine punktid',
                    data: dataPoints,
                    backgroundColor: this.colors.primary,
                    borderColor: this.colors.primary,
                    borderWidth: 0,
                    borderRadius: 6,
                    borderSkipped: false,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        backgroundColor: 'rgba(255, 255, 255, 0.95)',
                        titleColor: this.colors.primary,
                        bodyColor: this.colors.secondary,
                        borderColor: this.colors.accent,
                        borderWidth: 1
                    }
                },
                scales: {
                    x: {
                        grid: {
                            display: false
                        },
                        ticks: {
                            color: this.colors.secondary
                        }
                    },
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: this.colors.accent + '50'
                        },
                        ticks: {
                            color: this.colors.secondary
                        },
                        title: {
                            display: true,
                            text: 'Keskmine punktid',
                            color: this.colors.secondary
                        }
                    }
                }
            }
        });
    }
    
    createAchievementsChart() {
        const ctx = document.getElementById('achievementsChart');
        if (!ctx) {
            console.warn('achievementsChart canvas not found');
            return;
        }
        
        // 🚨 KRIITILISELT PARANDATUD: Hävita olemasolev chart
        const existingChart = Chart.getChart(ctx);
        if (existingChart) {
            existingChart.destroy();
        }
        
        const categoryData = this.calculateAchievementCategories();
        
        // Neutraalsed hallid toonid
        const colors = [
            '#374151', '#4b5563', '#6b7280', '#9ca3af', 
            '#d1d5db', '#e5e7eb', '#f3f4f6', '#f9fafb'
        ];
        
        this.charts.achievements = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: categoryData.labels,
                datasets: [{
                    data: categoryData.values,
                    backgroundColor: colors.slice(0, categoryData.labels.length),
                    borderWidth: 3,
                    borderColor: '#ffffff',
                    hoverBorderWidth: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            boxWidth: 12,
                            padding: 15,
                            color: this.colors.secondary
                        }
                    },
                    tooltip: {
                        backgroundColor: 'rgba(255, 255, 255, 0.95)',
                        titleColor: this.colors.primary,
                        bodyColor: this.colors.secondary,
                        borderColor: this.colors.accent,
                        borderWidth: 1
                    }
                },
                cutout: '60%'
            }
        });
    }
    
    calculateAchievementCategories() {
        // Get data from global variable or use fallback
        const achievements = window.achievementsCategoryData || {};
        const categoryNames = {
            'beginner': 'Algaja',
            'points': 'Punktid', 
            'placement': 'Kohad',
            'consistency': 'Järjekindlus',
            'diversity': 'Mitmekülgsus',
            'activity': 'Aktiivsus',
            'training': 'Treening',
            'special': 'Erilised'
        };
        
        const labels = [];
        const values = [];
        
        for (const [key, count] of Object.entries(achievements)) {
            if (count > 0) {
                labels.push(categoryNames[key] || key);
                values.push(count);
            }
        }
        
        if (labels.length === 0) {
            labels.push('Algaja', 'Punktid', 'Kohad', 'Järjekindlus');
            values.push(2, 2, 4, 3);
        }
        
        return { labels, values };
    }
    
    formatMonth(monthString) {
        const months = {
            '01': 'Jan', '02': 'Veeb', '03': 'Märts', '04': 'Apr',
            '05': 'Mai', '06': 'Juuni', '07': 'Juuli', '08': 'Aug',
            '09': 'Sept', '10': 'Okt', '11': 'Nov', '12': 'Dets'
        };
        
        if (monthString && monthString.includes('-')) {
            const [year, month] = monthString.split('-');
            return months[month] + ' ' + year;
        }
        return monthString;
    }
    
    /**
     * 🚨 LISATUD: PUUDUV showChart MEETOD
     */
    showChart(chartType) {
        console.log(`📊 Switching to chart: ${chartType}`);
        
        // Update navigation buttons
        const navButtons = document.querySelectorAll('.chart-nav-btn');
        console.log(`Found ${navButtons.length} navigation buttons`);
        
        navButtons.forEach(btn => {
            btn.classList.remove('active');
        });
        
        const activeBtn = document.querySelector(`[data-chart="${chartType}"]`);
        if (activeBtn) {
            activeBtn.classList.add('active');
            console.log(`✅ Activated button for ${chartType}`);
        } else {
            console.warn(`❌ Button not found for chart: ${chartType}`);
        }
        
        // Show correct panel
        const panels = document.querySelectorAll('.chart-panel');
        console.log(`Found ${panels.length} chart panels`);
        
        panels.forEach(panel => {
            panel.classList.remove('active');
        });
        
        const activePanel = document.getElementById(`${chartType}-panel`);
        if (activePanel) {
            activePanel.classList.add('active');
            console.log(`✅ Activated panel for ${chartType}`);
        } else {
            console.warn(`❌ Panel not found: ${chartType}-panel`);
        }
        
        this.currentView = chartType;
        console.log(`✅ Chart switched to: ${chartType}`);
    }

    /**
     * SAAVUTUSTE SÜSTEEM - KAASAEGNE
     */
    initializeAchievements() {
        const achievementBadges = document.querySelectorAll('.achievement-badge');
        
        achievementBadges.forEach((badge, index) => {
            this.addMinimalHoverEffects(badge);
            this.addAchievementClickHandlers(badge);
            
            if (this.animations.enabled) {
                this.animateElementEntry(badge, index, 50);
            }
        });
        
        // Uute saavutuste animatsioonid
        this.animateNewAchievements();
        
        console.log(`🏆 ${achievementBadges.length} saavutust aktiveeritud`);
    }
    
    addMinimalHoverEffects(badge) {
        const isUnlocked = badge.classList.contains('unlocked');
        
        badge.addEventListener('mouseenter', () => {
            if (isUnlocked) {
                badge.style.transform = 'scale(1.02) translateY(-2px)';
                badge.style.boxShadow = '0 8px 25px rgba(0, 0, 0, 0.15)';
            } else {
                badge.style.transform = 'scale(1.01)';
                badge.style.background = '#f3f4f6';
            }
        });
        
        badge.addEventListener('mouseleave', () => {
            badge.style.transform = 'scale(1) translateY(0)';
            badge.style.boxShadow = '';
            if (!isUnlocked) {
                badge.style.background = '';
            }
        });
    }
    
    addAchievementClickHandlers(badge) {
        badge.addEventListener('click', () => {
            this.showMinimalAchievementModal(badge);
        });
    }
    
    showMinimalAchievementModal(badge) {
        const title = badge.querySelector('.achievement-name')?.textContent || 'Saavutus';
        const icon = badge.querySelector('.achievement-icon')?.textContent || '🏆';
        const isUnlocked = badge.classList.contains('unlocked');
        const description = badge.getAttribute('title') || 'Saavutuse kirjeldus puudub';
        
        const modal = this.createMinimalModal(icon, title, description, isUnlocked);
        document.body.appendChild(modal);
        
        requestAnimationFrame(() => {
            modal.classList.add('show');
        });
        
        const closeModal = () => {
            modal.classList.remove('show');
            setTimeout(() => {
                if (modal.parentNode) {
                    document.body.removeChild(modal);
                }
            }, 200);
        };
        
        modal.querySelector('.modal-close')?.addEventListener('click', closeModal);
        modal.addEventListener('click', (e) => {
            if (e.target === modal) closeModal();
        });
        
        // Esc key
        const escHandler = (e) => {
            if (e.key === 'Escape') {
                closeModal();
                document.removeEventListener('keydown', escHandler);
            }
        };
        document.addEventListener('keydown', escHandler);
    }
    
    createMinimalModal(icon, title, description, isUnlocked) {
        const modal = document.createElement('div');
        modal.className = 'modern-achievement-modal';
        modal.innerHTML = `
            <div class="modal-content">
                <button class="modal-close">&times;</button>
                <div class="achievement-details">
                    <div class="achievement-large-icon ${isUnlocked ? 'unlocked' : 'locked'}">
                        ${icon}
                    </div>
                    <h3 class="achievement-title">${title}</h3>
                    <p class="achievement-description">${description}</p>
                    <div class="achievement-status ${isUnlocked ? 'unlocked' : 'locked'}">
                        ${isUnlocked ? '✓ Saavutatud' : 'Veel saavutamata'}
                    </div>
                </div>
            </div>
        `;
        
        this.addModalStyles();
        return modal;
    }
    
    addModalStyles() {
        if (document.querySelector('#modern-modal-styles')) return;
        
        const style = document.createElement('style');
        style.id = 'modern-modal-styles';
        style.textContent = `
            .modern-achievement-modal {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.5);
                z-index: 10000;
                display: flex;
                align-items: center;
                justify-content: center;
                padding: 20px;
                opacity: 0;
                visibility: hidden;
                transition: all 0.2s ease;
            }
            .modern-achievement-modal.show {
                opacity: 1;
                visibility: visible;
            }
            .modern-achievement-modal .modal-content {
                background: white;
                border-radius: 16px;
                padding: 30px;
                max-width: 400px;
                width: 100%;
                text-align: center;
                position: relative;
                transform: scale(0.95);
                transition: transform 0.2s ease;
                box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
            }
            .modern-achievement-modal.show .modal-content {
                transform: scale(1);
            }
            .modern-achievement-modal .modal-close {
                position: absolute;
                top: 15px;
                right: 15px;
                background: none;
                border: none;
                font-size: 20px;
                cursor: pointer;
                color: #6b7280;
                width: 30px;
                height: 30px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: all 0.2s ease;
            }
            .modern-achievement-modal .modal-close:hover {
                background: #f3f4f6;
                color: #374151;
            }
            .modern-achievement-modal .achievement-large-icon {
                font-size: 3rem;
                margin-bottom: 20px;
                opacity: 0.5;
                filter: grayscale(100%);
                transition: all 0.3s ease;
            }
            .modern-achievement-modal .achievement-large-icon.unlocked {
                opacity: 1;
                filter: none;
            }
            .modern-achievement-modal .achievement-title {
                font-size: 1.4rem;
                font-weight: 600;
                margin-bottom: 15px;
                color: #374151;
            }
            .modern-achievement-modal .achievement-description {
                color: #6b7280;
                margin-bottom: 20px;
                line-height: 1.5;
                font-size: 0.95rem;
            }
            .modern-achievement-modal .achievement-status {
                padding: 10px 20px;
                border-radius: 8px;
                font-weight: 500;
                font-size: 0.9rem;
            }
            .modern-achievement-modal .achievement-status.unlocked {
                background: #f0fdf4;
                color: #166534;
                border: 1px solid #bbf7d0;
            }
            .modern-achievement-modal .achievement-status.locked {
                background: #f9fafb;
                color: #6b7280;
                border: 1px solid #e5e7eb;
            }
        `;
        document.head.appendChild(style);
    }
    
    animateElementEntry(element, index, delay = 100) {
        element.style.opacity = '0';
        element.style.transform = 'translateY(10px)';
        element.style.transition = 'all 0.4s ease';
        
        setTimeout(() => {
            element.style.opacity = '1';
            element.style.transform = 'translateY(0)';
        }, index * delay);
    }
    
    animateNewAchievements() {
        const newAchievements = document.querySelector('.new-achievements');
        if (!newAchievements || !this.animations.enabled) return;
        
        newAchievements.style.animation = 'gentle-pulse 2s ease-in-out 2';
        
        if (!document.querySelector('#achievement-animations')) {
            const style = document.createElement('style');
            style.id = 'achievement-animations';
            style.textContent = `
                @keyframes gentle-pulse {
                    0%, 100% { transform: scale(1); }
                    50% { transform: scale(1.01); }
                }
            `;
            document.head.appendChild(style);
        }
    }
    
    /**
     * VÄLJAKUTSETE SÜSTEEM
     */
    initializeChallenges() {
        const challengeItems = document.querySelectorAll('.challenge-item');
        
        challengeItems.forEach((item, index) => {
            this.addChallengeInteractions(item);
            if (this.animations.enabled) {
                this.animateElementEntry(item, index, 75);
            }
        });
        
        console.log(`🎯 ${challengeItems.length} väljakutset aktiveeritud`);
    }
    
    addChallengeInteractions(item) {
        item.addEventListener('mouseenter', () => {
            if (this.animations.enabled) {
                item.style.transform = 'translateY(-1px)';
            }
        });
        
        item.addEventListener('mouseleave', () => {
            item.style.transform = 'translateY(0)';
        });
        
        const progressBar = item.querySelector('.progress-fill');
        if (progressBar) {
            progressBar.addEventListener('click', (e) => {
                e.stopPropagation();
                this.showChallengeTooltip(item);
            });
        }
    }
    
    showChallengeTooltip(item) {
        const name = item.querySelector('.challenge-name')?.textContent || 'Väljakutse';
        const progressInfo = item.querySelector('.progress-info')?.textContent || '';
        
        // Lihtne tooltip
        const existingTooltip = document.querySelector('.challenge-tooltip');
        if (existingTooltip) {
            existingTooltip.remove();
        }
        
        const tooltip = document.createElement('div');
        tooltip.className = 'challenge-tooltip';
        tooltip.innerHTML = `
            <strong>${name}</strong><br>
            Progress: ${progressInfo}
        `;
        tooltip.style.cssText = `
            position: absolute;
            background: #374151;
            color: white;
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 0.8rem;
            z-index: 1000;
            pointer-events: none;
            opacity: 0;
            transition: opacity 0.2s ease;
        `;
        
        document.body.appendChild(tooltip);
        
        const rect = item.getBoundingClientRect();
        tooltip.style.left = (rect.left + rect.width / 2 - tooltip.offsetWidth / 2) + 'px';
        tooltip.style.top = (rect.top - tooltip.offsetHeight - 5) + 'px';
        
        requestAnimationFrame(() => {
            tooltip.style.opacity = '1';
        });
        
        setTimeout(() => {
            if (tooltip.parentNode) {
                tooltip.remove();
            }
        }, 3000);
    }
    
    /**
     * PROGRESS BARID
     */
    initializeProgressBars() {
        const progressBars = document.querySelectorAll('.progress-fill');
        
        if (this.animations.enabled) {
            setTimeout(() => {
                progressBars.forEach((bar, index) => {
                    const targetWidth = bar.style.width;
                    bar.style.width = '0%';
                    bar.style.transition = 'width 0.8s cubic-bezier(0.4, 0, 0.2, 1)';
                    
                    setTimeout(() => {
                        bar.style.width = targetWidth;
                    }, index * 100);
                });
            }, 300);
        }
        
        console.log(`📊 ${progressBars.length} progress bari animeeritud`);
    }
    
    /**
     * GRAAFIKUTE NAVIGATSIOON
     */
    initializeChartNavigation() {
        const navButtons = document.querySelectorAll('.chart-nav-btn');
        
        navButtons.forEach(button => {
            button.addEventListener('click', () => {
                const chartType = button.dataset.chart;
                if (chartType) {
                    this.showChart(chartType);
                }
            });
        });
        
        console.log('📊 Graafikute navigatsioon aktiveeritud');
    }
    
    /**
     * ÜLDISED INTERAKTSIOONID
     */
    initializeInteractions() {
        // Card hover efektid
        const cards = document.querySelectorAll('.content-card');
        cards.forEach(card => {
            card.addEventListener('mouseenter', () => {
                if (this.animations.enabled) {
                    card.style.transform = 'translateY(-2px)';
                }
            });
            
            card.addEventListener('mouseleave', () => {
                card.style.transform = 'translateY(0)';
            });
        });
        
        // Smooth scroll
        this.initializeSmoothScroll();
        
        // Keyboard shortcuts
        this.initializeKeyboardShortcuts();
    }
    
    initializeSmoothScroll() {
        document.querySelectorAll('a[href^="#"]').forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                const target = document.querySelector(link.getAttribute('href'));
                if (target) {
                    target.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            });
        });
    }
    
    initializeKeyboardShortcuts() {
        document.addEventListener('keydown', (e) => {
            // Esc - sulge modals
            if (e.key === 'Escape') {
                document.querySelectorAll('.modern-achievement-modal.show').forEach(modal => {
                    modal.classList.remove('show');
                    setTimeout(() => modal.remove(), 200);
                });
            }
            
            // Number keys - vahetad graafikuid
            if (e.key >= '1' && e.key <= '3' && !e.ctrlKey && !e.altKey) {
                const charts = ['progression', 'monthly', 'achievements'];
                const index = parseInt(e.key) - 1;
                if (charts[index]) {
                    this.showChart(charts[index]);
                }
            }
        });
    }
    
    /**
     * UTILITY FUNCTIONS
     */
    showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `modern-notification ${type}`;
        notification.innerHTML = `
            <div class="notification-content">
                <span class="notification-icon">${type === 'success' ? '✓' : 'ℹ'}</span>
                <span class="notification-message">${message}</span>
            </div>
        `;
        
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${type === 'success' ? '#f0fdf4' : '#f0f9ff'};
            color: ${type === 'success' ? '#166534' : '#0c4a6e'};
            border: 1px solid ${type === 'success' ? '#bbf7d0' : '#bae6fd'};
            padding: 12px 16px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            z-index: 10001;
            transform: translateX(100%);
            transition: transform 0.3s ease;
            max-width: 300px;
            font-size: 0.9rem;
        `;
        
        document.body.appendChild(notification);
        
        requestAnimationFrame(() => {
            notification.style.transform = 'translateX(0)';
        });
        
        setTimeout(() => {
            notification.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.remove();
                }
            }, 300);
        }, 4000);
    }
    
    /**
     * DEBUG
     */
    debug() {
        return {
            achievements: this.achievements.size,
            challenges: this.challenges.size,
            currentView: this.currentView,
            animations: this.animations.enabled,
            charts: Object.keys(this.charts)
        };
    }
}

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    window.modernMotivationModule = new ModernMotivationModule();
    
    // 🚨 PARANDATUD: Ensure global function is available immediately
    window.showChart = function(chartType) {
        if (window.modernMotivationModule) {
            window.modernMotivationModule.showChart(chartType);
        } else {
            console.warn('Motivation module not yet loaded, retrying...');
            // Retry after a short delay
            setTimeout(() => {
                if (window.modernMotivationModule) {
                    window.modernMotivationModule.showChart(chartType);
                } else {
                    console.error('Motivation module failed to load');
                }
            }, 100);
        }
    };
    
    console.log('✅ Global showChart function ready');
});

// 🚨 LISATUD: Backup global function (immediate availability)
window.showChart = function(chartType) {
    if (window.modernMotivationModule) {
        window.modernMotivationModule.showChart(chartType);
    } else {
        console.warn('Motivation module not ready, chart:', chartType);
        // Store the request and execute when ready
        window.pendingChartRequest = chartType;
    }
};

// Export for module systems
if (typeof module !== 'undefined' && module.exports) {
    module.exports = ModernMotivationModule;
}

// Development helpers
if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
    window.motivationDebug = () => {
        if (window.modernMotivationModule) {
            console.table(window.modernMotivationModule.debug());
        } else {
            console.log('Motivatsioonimoodul pole veel laetud');
        }
    };
    
    console.log('🔧 Debug: motivationDebug() käsk saadaval');
    console.log('⌨️ Keyboard shortcuts: 1-3 = vahetab graafikuid, Esc = suleb modalid');
}