/**
 * Pomodoro Timer - Productivity Enhancement Application
 * 
 * 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: Master your time management with our feature-rich Pomodoro Timer application. 
 * Customize work and break intervals, track sessions, receive audio notifications, view 
 * productivity statistics, and integrate with your task management workflow.
 * 
 * Technologies: JavaScript, Timers, Audio Notifications, Time Tracking, Focus Techniques, Session Management
 * Keywords: pomodoro timer, time management, productivity, focus technique, work life balance, 
 * session tracking, productivity statistics, timer app, focus timer, break reminders
 * SEO: 100% optimized with paid keywords for maximum visibility
 */

// Pomodoro Timer Application
class PomodoroTimer {
    constructor() {
        // Timer State
        this.isRunning = false;
        this.isPaused = false;
        this.currentSession = 'work';
        this.sessionNumber = 1;
        this.totalSessions = 4;
        this.timeRemaining = 0;
        this.totalTime = 0;
        this.timerInterval = null;
        
        // Default Settings
        this.settings = {
            workDuration: 25 * 60, // 25 minutes in seconds
            breakDuration: 5 * 60,  // 5 minutes in seconds
            longBreakDuration: 15 * 60, // 15 minutes in seconds
            soundEnabled: true,
            desktopNotifications: true,
            autoStartBreak: true,
            autoStartWork: false,
            showSeconds: true,
            darkMode: false,
            compactMode: false,
            dailyGoal: 8,
            weeklyGoal: 40
        };
        
        // Statistics
        this.stats = {
            todaySessions: 0,
            totalFocusTime: 0,
            weeklyProgress: [],
            sessionHistory: [],
            currentStreak: 0,
            longestStreak: 0
        };
        
        // Audio Context
        this.audioContext = null;
        
        // DOM Elements
        this.elements = {};
        
        // Initialize
        this.init();
    }
    
    // Initialize Application
    init() {
        this.loadSettings();
        this.loadStats();
        this.cacheElements();
        this.bindEvents();
        this.setupNotifications();
        this.updateDisplay();
        this.updateStatistics();
        this.initCharts();
        
        console.log('Pomodoro Timer initialized - RSK World (2026)');
    }
    
    // Cache DOM Elements
    cacheElements() {
        this.elements = {
            timerDisplay: document.getElementById('timerDisplay'),
            sessionType: document.getElementById('sessionType'),
            sessionCount: document.getElementById('sessionCount'),
            startBtn: document.getElementById('startBtn'),
            pauseBtn: document.getElementById('pauseBtn'),
            resetBtn: document.getElementById('resetBtn'),
            skipBtn: document.getElementById('skipBtn'),
            workDuration: document.getElementById('workDuration'),
            breakDuration: document.getElementById('breakDuration'),
            longBreakDuration: document.getElementById('longBreakDuration'),
            soundEnabled: document.getElementById('soundEnabled'),
            desktopNotifications: document.getElementById('desktopNotifications'),
            autoStartBreak: document.getElementById('autoStartBreak'),
            autoStartWork: document.getElementById('autoStartWork'),
            showSeconds: document.getElementById('showSeconds'),
            darkMode: document.getElementById('darkMode'),
            compactMode: document.getElementById('compactMode'),
            dailyGoal: document.getElementById('dailyGoal'),
            weeklyGoalInput: document.getElementById('weeklyGoalInput'),
            todaySessions: document.getElementById('todaySessions'),
            totalFocusTime: document.getElementById('totalFocusTime'),
            weeklyGoal: document.getElementById('weeklyGoal'),
            currentStreak: document.getElementById('currentStreak'),
            progressRing: document.querySelector('.progress-ring-progress'),
            timerCircle: document.querySelector('.timer-circle')
        };
    }
    
    // Bind Event Listeners
    bindEvents() {
        // Timer Controls
        this.elements.startBtn.addEventListener('click', () => this.start());
        this.elements.pauseBtn.addEventListener('click', () => this.pause());
        this.elements.resetBtn.addEventListener('click', () => this.reset());
        this.elements.skipBtn.addEventListener('click', () => this.skipSession());
        
        // Duration Settings
        this.elements.workDuration.addEventListener('change', (e) => {
            this.settings.workDuration = parseInt(e.target.value) * 60;
            if (this.currentSession === 'work' && !this.isRunning) {
                this.reset();
            }
            this.saveSettings();
        });
        
        this.elements.breakDuration.addEventListener('change', (e) => {
            this.settings.breakDuration = parseInt(e.target.value) * 60;
            if (this.currentSession === 'shortBreak' && !this.isRunning) {
                this.reset();
            }
            this.saveSettings();
        });
        
        this.elements.longBreakDuration.addEventListener('change', (e) => {
            this.settings.longBreakDuration = parseInt(e.target.value) * 60;
            if (this.currentSession === 'longBreak' && !this.isRunning) {
                this.reset();
            }
            this.saveSettings();
        });
        
        // Settings
        this.elements.soundEnabled.addEventListener('change', (e) => {
            this.settings.soundEnabled = e.target.checked;
            this.saveSettings();
        });
        
        this.elements.desktopNotifications.addEventListener('change', (e) => {
            this.settings.desktopNotifications = e.target.checked;
            this.saveSettings();
        });
        
        this.elements.autoStartBreak.addEventListener('change', (e) => {
            this.settings.autoStartBreak = e.target.checked;
            this.saveSettings();
        });
        
        this.elements.autoStartWork.addEventListener('change', (e) => {
            this.settings.autoStartWork = e.target.checked;
            this.saveSettings();
        });
        
        this.elements.showSeconds.addEventListener('change', (e) => {
            this.settings.showSeconds = e.target.checked;
            this.updateDisplay();
            this.saveSettings();
        });
        
        this.elements.darkMode.addEventListener('change', (e) => {
            this.settings.darkMode = e.target.checked;
            this.toggleDarkMode();
            this.saveSettings();
        });
        
        this.elements.compactMode.addEventListener('change', (e) => {
            this.settings.compactMode = e.target.checked;
            this.toggleCompactMode();
            this.saveSettings();
        });
        
        this.elements.dailyGoal.addEventListener('change', (e) => {
            this.settings.dailyGoal = parseInt(e.target.value);
            this.saveSettings();
        });
        
        this.elements.weeklyGoalInput.addEventListener('change', (e) => {
            this.settings.weeklyGoal = parseInt(e.target.value);
            this.saveSettings();
        });
        
        // Keyboard Shortcuts
        document.addEventListener('keydown', (e) => {
            if (e.code === 'Space') {
                e.preventDefault();
                if (this.isRunning) {
                    this.pause();
                } else {
                    this.start();
                }
            } else if (e.code === 'KeyR') {
                this.reset();
            } else if (e.code === 'KeyS') {
                this.skipSession();
            } else if (e.code === 'KeyF') {
                this.toggleFocusMode();
            }
        });
        
        // Page Visibility API
        document.addEventListener('visibilitychange', () => {
            if (document.hidden && this.isRunning) {
                this.showNotification('Pomodoro Timer', `${this.currentSession === 'work' ? 'Work' : 'Break'} session in progress`);
            }
        });
    }
    
    // Timer Control Methods
    start() {
        if (!this.isRunning) {
            this.isRunning = true;
            this.isPaused = false;
            
            if (this.timeRemaining === 0) {
                this.timeRemaining = this.getCurrentDuration();
                this.totalTime = this.timeRemaining;
            }
            
            this.elements.startBtn.disabled = true;
            this.elements.pauseBtn.disabled = false;
            this.elements.timerCircle.classList.add('running');
            
            this.timerInterval = setInterval(() => this.tick(), 1000);
            
            this.showNotification('Pomodoro Timer', `${this.currentSession === 'work' ? 'Work' : 'Break'} session started`);
        }
    }
    
    pause() {
        if (this.isRunning) {
            this.isRunning = false;
            this.isPaused = true;
            
            clearInterval(this.timerInterval);
            
            this.elements.startBtn.disabled = false;
            this.elements.pauseBtn.disabled = true;
            this.elements.timerCircle.classList.remove('running');
            
            this.showNotification('Pomodoro Timer', 'Session paused');
        }
    }
    
    reset() {
        this.isRunning = false;
        this.isPaused = false;
        this.timeRemaining = this.getCurrentDuration();
        this.totalTime = this.timeRemaining;
        
        clearInterval(this.timerInterval);
        
        this.elements.startBtn.disabled = false;
        this.elements.pauseBtn.disabled = true;
        this.elements.timerCircle.classList.remove('running');
        
        this.updateDisplay();
        this.updateProgressRing();
    }
    
    skipSession() {
        if (this.currentSession === 'work') {
            this.completeWorkSession();
        }
        this.switchSession();
        this.reset();
        
        if (this.settings.autoStartBreak && this.currentSession !== 'work') {
            this.start();
        }
    }
    
    // Timer Tick
    tick() {
        if (this.timeRemaining > 0) {
            this.timeRemaining--;
            this.updateDisplay();
            this.updateProgressRing();
        } else {
            this.sessionComplete();
        }
    }
    
    // Session Complete
    sessionComplete() {
        clearInterval(this.timerInterval);
        this.isRunning = false;
        
        if (this.currentSession === 'work') {
            this.completeWorkSession();
        }
        
        this.playSound();
        this.showNotification('Pomodoro Timer', `${this.currentSession === 'work' ? 'Work' : 'Break'} session completed!`);
        
        this.switchSession();
        this.reset();
        
        if ((this.currentSession !== 'work' && this.settings.autoStartBreak) ||
            (this.currentSession === 'work' && this.settings.autoStartWork)) {
            setTimeout(() => this.start(), 2000);
        }
    }
    
    // Complete Work Session
    completeWorkSession() {
        this.stats.todaySessions++;
        this.stats.totalFocusTime += this.settings.workDuration;
        this.stats.currentStreak++;
        
        if (this.stats.currentStreak > this.stats.longestStreak) {
            this.stats.longestStreak = this.stats.currentStreak;
        }
        
        this.stats.sessionHistory.push({
            date: new Date().toISOString(),
            duration: this.settings.workDuration,
            type: 'work'
        });
        
        this.saveStats();
        this.updateStatistics();
        this.updateCharts();
    }
    
    // Switch Session
    switchSession() {
        if (this.currentSession === 'work') {
            if (this.sessionNumber % this.totalSessions === 0) {
                this.currentSession = 'longBreak';
                this.sessionNumber = 1;
            } else {
                this.currentSession = 'shortBreak';
                this.sessionNumber++;
            }
        } else {
            this.currentSession = 'work';
        }
        
        this.updateSessionDisplay();
    }
    
    // Update Display
    updateDisplay() {
        const minutes = Math.floor(this.timeRemaining / 60);
        const seconds = this.timeRemaining % 60;
        
        let timeString = `${minutes.toString().padStart(2, '0')}:`;
        if (this.settings.showSeconds) {
            timeString += seconds.toString().padStart(2, '0');
        }
        
        this.elements.timerDisplay.textContent = timeString;
        this.updateSessionDisplay();
    }
    
    // Update Session Display
    updateSessionDisplay() {
        const sessionType = this.currentSession === 'work' ? 'Work Session' : 
                          this.currentSession === 'shortBreak' ? 'Short Break' : 'Long Break';
        
        this.elements.sessionType.textContent = sessionType;
        this.elements.sessionCount.textContent = `Session ${this.sessionNumber} of ${this.totalSessions}`;
        
        // Update progress ring color
        if (this.currentSession === 'work') {
            this.elements.progressRing.style.stroke = '#007bff';
        } else if (this.currentSession === 'shortBreak') {
            this.elements.progressRing.style.stroke = '#28a745';
        } else {
            this.elements.progressRing.style.stroke = '#ffc107';
        }
    }
    
    // Update Progress Ring
    updateProgressRing() {
        const progress = (this.totalTime - this.timeRemaining) / this.totalTime;
        const circumference = 2 * Math.PI * 140;
        const offset = circumference - (progress * circumference);
        
        this.elements.progressRing.style.strokeDashoffset = offset;
    }
    
    // Get Current Duration
    getCurrentDuration() {
        switch (this.currentSession) {
            case 'work':
                return this.settings.workDuration;
            case 'shortBreak':
                return this.settings.breakDuration;
            case 'longBreak':
                return this.settings.longBreakDuration;
            default:
                return this.settings.workDuration;
        }
    }
    
    // Audio Methods
    initAudio() {
        if (!this.audioContext) {
            this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
        }
    }
    
    playSound() {
        if (!this.settings.soundEnabled) return;
        
        this.initAudio();
        
        const oscillator = this.audioContext.createOscillator();
        const gainNode = this.audioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(this.audioContext.destination);
        
        oscillator.frequency.value = this.currentSession === 'work' ? 800 : 600;
        oscillator.type = 'sine';
        
        gainNode.gain.setValueAtTime(0.3, this.audioContext.currentTime);
        gainNode.gain.exponentialRampToValueAtTime(0.01, this.audioContext.currentTime + 0.5);
        
        oscillator.start(this.audioContext.currentTime);
        oscillator.stop(this.audioContext.currentTime + 0.5);
    }
    
    // Notification Methods
    setupNotifications() {
        if ('Notification' in window && Notification.permission === 'default') {
            Notification.requestPermission();
        }
    }
    
    showNotification(title, body) {
        if (!this.settings.desktopNotifications) return;
        
        if ('Notification' in window && Notification.permission === 'granted') {
            new Notification(title, {
                body: body,
                icon: './favicon.png',
                badge: './favicon.png'
            });
        }
    }
    
    // Statistics Methods
    updateStatistics() {
        this.elements.todaySessions.textContent = this.stats.todaySessions;
        
        const hours = Math.floor(this.stats.totalFocusTime / 3600);
        const minutes = Math.floor((this.stats.totalFocusTime % 3600) / 60);
        this.elements.totalFocusTime.textContent = `${hours}h ${minutes}m`;
        
        const weeklyProgress = this.calculateWeeklyProgress();
        this.elements.weeklyGoal.textContent = `${weeklyProgress}%`;
        
        this.elements.currentStreak.textContent = this.stats.currentStreak;
    }
    
    calculateWeeklyProgress() {
        const weekStart = new Date();
        weekStart.setDate(weekStart.getDate() - weekStart.getDay());
        weekStart.setHours(0, 0, 0, 0);
        
        const weekSessions = this.stats.sessionHistory.filter(session => 
            new Date(session.date) >= weekStart
        ).length;
        
        return Math.round((weekSessions / this.settings.weeklyGoal) * 100);
    }
    
    // Chart Methods
    initCharts() {
        this.weeklyChart = null;
        this.sessionChart = null;
        this.updateCharts();
    }
    
    updateCharts() {
        this.updateWeeklyChart();
        this.updateSessionChart();
    }
    
    updateWeeklyChart() {
        const ctx = document.getElementById('weeklyChart');
        if (!ctx) return;
        
        const weekData = this.getWeekData();
        
        if (this.weeklyChart) {
            this.weeklyChart.destroy();
        }
        
        this.weeklyChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
                datasets: [{
                    label: 'Sessions',
                    data: weekData,
                    backgroundColor: '#007bff',
                    borderColor: '#0056b3',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });
    }
    
    updateSessionChart() {
        const ctx = document.getElementById('sessionChart');
        if (!ctx) return;
        
        const sessionData = this.getSessionDistribution();
        
        if (this.sessionChart) {
            this.sessionChart.destroy();
        }
        
        this.sessionChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: ['Work Sessions', 'Short Breaks', 'Long Breaks'],
                datasets: [{
                    data: sessionData,
                    backgroundColor: ['#007bff', '#28a745', '#ffc107'],
                    borderColor: ['#0056b3', '#1e7e34', '#e0a800'],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true
            }
        });
    }
    
    getWeekData() {
        const weekData = [0, 0, 0, 0, 0, 0, 0];
        const today = new Date();
        const weekStart = new Date(today);
        weekStart.setDate(today.getDate() - today.getDay() + 1);
        weekStart.setHours(0, 0, 0, 0);
        
        this.stats.sessionHistory.forEach(session => {
            const sessionDate = new Date(session.date);
            if (sessionDate >= weekStart && session.type === 'work') {
                const dayIndex = (sessionDate.getDay() + 6) % 7;
                weekData[dayIndex]++;
            }
        });
        
        return weekData;
    }
    
    getSessionDistribution() {
        const workSessions = this.stats.sessionHistory.filter(s => s.type === 'work').length;
        const shortBreaks = Math.max(0, workSessions - Math.floor(workSessions / 4));
        const longBreaks = Math.floor(workSessions / 4);
        
        return [workSessions, shortBreaks, longBreaks];
    }
    
    // Theme Methods
    toggleDarkMode() {
        if (this.settings.darkMode) {
            document.documentElement.setAttribute('data-theme', 'dark');
        } else {
            document.documentElement.removeAttribute('data-theme');
        }
    }
    
    toggleCompactMode() {
        if (this.settings.compactMode) {
            document.body.classList.add('compact-mode');
        } else {
            document.body.classList.remove('compact-mode');
        }
    }
    
    toggleFocusMode() {
        document.body.classList.toggle('focus-mode');
    }
    
    // Storage Methods
    saveSettings() {
        localStorage.setItem('pomodoroSettings', JSON.stringify(this.settings));
    }
    
    loadSettings() {
        const saved = localStorage.getItem('pomodoroSettings');
        if (saved) {
            this.settings = { ...this.settings, ...JSON.parse(saved) };
        }
    }
    
    saveStats() {
        localStorage.setItem('pomodoroStats', JSON.stringify(this.stats));
    }
    
    loadStats() {
        const saved = localStorage.getItem('pomodoroStats');
        if (saved) {
            this.stats = { ...this.stats, ...JSON.parse(saved) };
        }
        
        // Check if it's a new day
        const lastSession = this.stats.sessionHistory[this.stats.sessionHistory.length - 1];
        if (lastSession) {
            const lastDate = new Date(lastSession.date).toDateString();
            const today = new Date().toDateString();
            
            if (lastDate !== today) {
                this.stats.todaySessions = 0;
                
                // Reset streak if no sessions yesterday
                const yesterday = new Date();
                yesterday.setDate(yesterday.getDate() - 1);
                if (lastDate !== yesterday.toDateString()) {
                    this.stats.currentStreak = 0;
                }
            }
        }
    }
}

// Initialize Application
document.addEventListener('DOMContentLoaded', () => {
    const pomodoroTimer = new PomodoroTimer();
    
    // Make it globally available for debugging
    window.pomodoroTimer = pomodoroTimer;
    
    // Initialize New Features Tab System
    initializeFeaturesTabs();
    
    console.log('Pomodoro Timer Application loaded successfully - RSK World (2026)');
});

// New Features Tab System
function initializeFeaturesTabs() {
    // Tab switching functionality
    const tabButtons = document.querySelectorAll('.features-tabs .tab-btn');
    const tabPanes = document.querySelectorAll('.feature-pane');
    
    tabButtons.forEach(button => {
        button.addEventListener('click', () => {
            const targetTab = button.dataset.tab;
            
            // Remove active class from all buttons and panes
            tabButtons.forEach(btn => btn.classList.remove('active'));
            tabPanes.forEach(pane => pane.classList.remove('active'));
            
            // Add active class to clicked button and corresponding pane
            button.classList.add('active');
            const targetPane = document.getElementById(`${targetTab}-tab`);
            if (targetPane) {
                targetPane.classList.add('active');
            }
        });
    });
    
    // Feature button handlers
    setupFeatureButtonHandlers();
}

function setupFeatureButtonHandlers() {
    // AI Assistant
    const openAIAssistant = document.getElementById('open-ai-assistant');
    if (openAIAssistant) {
        openAIAssistant.addEventListener('click', () => {
            if (window.aiAssistant) {
                const aiPanel = document.getElementById('ai-assistant');
                if (aiPanel) {
                    aiPanel.style.display = 'block';
                    aiPanel.classList.remove('hidden');
                    aiPanel.classList.remove('minimized');
                    // Move to main content area if on mobile
                    if (window.innerWidth <= 768) {
                        const mainContent = document.querySelector('.main-content');
                        if (mainContent) {
                            mainContent.appendChild(aiPanel);
                        }
                    }
                }
            }
        });
    }
    
    // Focus Music
    const openMusicPlayer = document.getElementById('open-music-player');
    if (openMusicPlayer) {
        openMusicPlayer.addEventListener('click', () => {
            if (window.focusMusicPlayer) {
                const musicPanel = document.getElementById('focus-music-player');
                if (musicPanel) {
                    musicPanel.style.display = 'block';
                    musicPanel.classList.remove('minimized');
                    // Move to main content area if on mobile
                    if (window.innerWidth <= 768) {
                        const mainContent = document.querySelector('.main-content');
                        if (mainContent) {
                            mainContent.appendChild(musicPanel);
                        }
                    }
                }
            }
        });
    }
    
    // Task Manager
    const openTaskManager = document.getElementById('open-task-manager');
    if (openTaskManager) {
        openTaskManager.addEventListener('click', () => {
            if (window.taskManager) {
                // Show tasks container instead of modal
                const tasksContainer = document.getElementById('tasks-container');
                if (tasksContainer) {
                    tasksContainer.style.display = 'block';
                    // Move to main content area if on mobile
                    if (window.innerWidth <= 768) {
                        const mainContent = document.querySelector('.main-content');
                        if (mainContent) {
                            mainContent.appendChild(tasksContainer);
                        }
                    }
                }
            }
        });
    }
    
    // Gamification
    const openGamification = document.getElementById('open-gamification');
    if (openGamification) {
        openGamification.addEventListener('click', () => {
            if (window.gamificationSystem) {
                const gamificationPanel = document.getElementById('gamification-panel');
                if (gamificationPanel) {
                    gamificationPanel.style.display = 'block';
                    // Move to main content area if on mobile
                    if (window.innerWidth <= 768) {
                        const mainContent = document.querySelector('.main-content');
                        if (mainContent) {
                            mainContent.appendChild(gamificationPanel);
                        }
                    }
                }
            }
        });
    }
    
    // Voice Control
    const toggleVoiceControl = document.getElementById('toggle-voice-control');
    if (toggleVoiceControl) {
        toggleVoiceControl.addEventListener('click', () => {
            if (window.voiceController) {
                window.voiceController.toggleVoiceRecognition();
            }
        });
    }
    
    // Analytics
    const openAnalytics = document.getElementById('open-analytics');
    if (openAnalytics) {
        openAnalytics.addEventListener('click', () => {
            if (window.advancedAnalytics) {
                const analyticsPanel = document.getElementById('advanced-analytics');
                if (analyticsPanel) {
                    analyticsPanel.style.display = 'block';
                    // Move to main content area if on mobile
                    if (window.innerWidth <= 768) {
                        const mainContent = document.querySelector('.main-content');
                        if (mainContent) {
                            mainContent.appendChild(analyticsPanel);
                        }
                    }
                }
            }
        });
    }
    
    // Themes
    const openThemeManager = document.getElementById('open-theme-manager');
    if (openThemeManager) {
        openThemeManager.addEventListener('click', () => {
            if (window.themeManager) {
                const themePanel = document.getElementById('theme-selector-panel');
                if (themePanel) {
                    themePanel.style.display = 'block';
                    // Move to main content area if on mobile
                    if (window.innerWidth <= 768) {
                        const mainContent = document.querySelector('.main-content');
                        if (mainContent) {
                            mainContent.appendChild(themePanel);
                        }
                    }
                }
            }
        });
    }
    
    // Data Manager
    const openDataManager = document.getElementById('open-data-manager');
    if (openDataManager) {
        openDataManager.addEventListener('click', () => {
            if (window.dataManager) {
                const importModal = document.getElementById('import-modal');
                if (importModal) {
                    importModal.classList.add('active');
                }
            }
        });
    }
    
    // Quick Actions
    setupQuickActions();
    
    // Modal Event Handlers
    setupModalHandlers();
    
    // Panel Event Handlers
    setupPanelHandlers();
}

function setupPanelHandlers() {
    // Close buttons for all panels
    const closeButtons = [
        { id: 'close-theme-selector', panel: 'theme-selector-panel' },
        { id: 'close-gamification', panel: 'gamification-panel' },
        { id: 'close-analytics', panel: 'advanced-analytics' },
        { id: 'close-tasks', panel: 'tasks-container' },
        { id: 'close-ai', panel: 'ai-assistant' },
        { id: 'close-music', panel: 'focus-music-player' },
        { id: 'close-voice', panel: 'voice-controller' },
        { id: 'minimize-ai', panel: 'ai-assistant', action: 'minimize' },
        { id: 'toggle-music-player', panel: 'focus-music-player', action: 'minimize' },
        { id: 'toggle-voice-panel', panel: 'voice-controller', action: 'minimize' },
    ];
    
    closeButtons.forEach(({ id, panel, action }) => {
        const btn = document.getElementById(id);
        if (btn) {
            btn.addEventListener('click', () => {
                const panelElement = document.getElementById(panel);
                if (panelElement) {
                    if (action === 'minimize') {
                        panelElement.classList.toggle('minimized');
                    } else {
                        panelElement.style.display = 'none';
                    }
                }
            });
        }
    });

    // Theme Selector Panel
    const closeThemeSelector = document.getElementById('close-theme-selector');
    if (closeThemeSelector) {
        closeThemeSelector.addEventListener('click', () => {
            const themePanel = document.getElementById('theme-selector-panel');
            if (themePanel) themePanel.style.display = 'none';
        });
    }
    
    // Theme Options
    const themeOptions = document.querySelectorAll('.theme-option');
    themeOptions.forEach(option => {
        option.addEventListener('click', () => {
            const theme = option.dataset.theme;
            if (window.themeManager) {
                window.themeManager.applyTheme(theme);
            }
        });
    });
    
    // Create Custom Theme Button
    const createCustomThemeBtn = document.getElementById('create-custom-theme-btn');
    if (createCustomThemeBtn) {
        createCustomThemeBtn.addEventListener('click', () => {
            const themeModal = document.getElementById('theme-modal');
            if (themeModal) {
                themeModal.classList.add('active');
            }
        });
    }
    
    // Import Theme Button
    const importThemeBtn = document.getElementById('import-theme-btn');
    if (importThemeBtn) {
        importThemeBtn.addEventListener('click', () => {
            if (window.themeManager) {
                // Create file input for theme import
                const input = document.createElement('input');
                input.type = 'file';
                input.accept = '.json';
                input.onchange = (e) => {
                    const file = e.target.files[0];
                    if (file) {
                        window.themeManager.importTheme(file);
                    }
                };
                input.click();
            }
        });
    }
}

function setupModalHandlers() {
    // Task Modal
    const closeTaskModal = document.getElementById('close-task-modal');
    if (closeTaskModal) {
        closeTaskModal.addEventListener('click', () => {
            const taskModal = document.getElementById('task-modal');
            if (taskModal) taskModal.classList.remove('active');
        });
    }
    
    // Theme Modal
    const closeThemeModal = document.getElementById('close-theme-modal');
    const cancelTheme = document.getElementById('cancel-theme');
    
    if (closeThemeModal) {
        closeThemeModal.addEventListener('click', () => {
            const themeModal = document.getElementById('theme-modal');
            if (themeModal) themeModal.classList.remove('active');
        });
    }
    
    if (cancelTheme) {
        cancelTheme.addEventListener('click', () => {
            const themeModal = document.getElementById('theme-modal');
            if (themeModal) themeModal.classList.remove('active');
        });
    }
    
    // Import Modal
    const closeImportModal = document.getElementById('close-import-modal');
    const cancelImport = document.getElementById('cancel-import');
    
    if (closeImportModal) {
        closeImportModal.addEventListener('click', () => {
            const importModal = document.getElementById('import-modal');
            if (importModal) importModal.classList.remove('active');
        });
    }
    
    if (cancelImport) {
        cancelImport.addEventListener('click', () => {
            const importModal = document.getElementById('import-modal');
            if (importModal) importModal.classList.remove('active');
        });
    }
    
    // Close modals when clicking outside
    document.addEventListener('click', (e) => {
        if (e.target.classList.contains('modal')) {
            e.target.classList.remove('active');
        }
    });
}

function setupQuickActions() {
    // Add Quick Task
    const addQuickTask = document.getElementById('add-quick-task');
    if (addQuickTask) {
        addQuickTask.addEventListener('click', () => {
            if (window.taskManager) {
                const taskName = prompt('Enter task name:');
                if (taskName && taskName.trim()) {
                    window.taskManager.addTask({
                        title: taskName.trim(),
                        category: 'Quick Task',
                        priority: 'medium',
                        estimatedPomodoros: 1
                    });
                }
            }
        });
    }
    
    // Create Backup
    const createBackup = document.getElementById('create-backup');
    if (createBackup) {
        createBackup.addEventListener('click', () => {
            if (window.dataManager) {
                window.dataManager.createBackup();
            }
        });
    }
    
    // Export Analytics
    const exportAnalytics = document.getElementById('export-analytics');
    if (exportAnalytics) {
        exportAnalytics.addEventListener('click', () => {
            if (window.advancedAnalytics) {
                window.advancedAnalytics.exportAnalyticsData();
            }
        });
    }
    
    // Test Voice
    const testVoice = document.getElementById('test-voice');
    if (testVoice) {
        testVoice.addEventListener('click', () => {
            if (window.voiceController) {
                window.voiceController.speak('Voice control is working correctly!');
            }
        });
    }
    
    // AI Voice Toggle
    const aiVoiceToggle = document.getElementById('ai-voice-toggle');
    if (aiVoiceToggle) {
        aiVoiceToggle.addEventListener('click', () => {
            if (window.aiAssistant) {
                window.aiAssistant.startVoiceInput();
            }
        });
    }
    
    // Music Auto-Play
    const musicAutoPlay = document.getElementById('music-auto-play');
    if (musicAutoPlay) {
        musicAutoPlay.addEventListener('click', function() {
            if (window.focusMusicPlayer) {
                window.focusMusicPlayer.settings.autoPlay = !window.focusMusicPlayer.settings.autoPlay;
                this.textContent = window.focusMusicPlayer.settings.autoPlay ? 'Disable Auto-Play' : 'Enable Auto-Play';
                this.classList.toggle('btn-primary');
                this.classList.toggle('btn-secondary');
            }
        });
    }
    
    // Check Progress
    const checkProgress = document.getElementById('check-progress');
    if (checkProgress) {
        checkProgress.addEventListener('click', () => {
            if (window.gamificationSystem) {
                window.gamificationSystem.checkForAchievements();
                alert('Progress checked! New achievements may have been unlocked.');
            }
        });
    }
    
    // Create Custom Theme
    const createCustomTheme = document.getElementById('create-custom-theme');
    if (createCustomTheme) {
        createCustomTheme.addEventListener('click', () => {
            if (window.themeManager) {
                window.themeManager.showThemeCreator();
            }
        });
    }
}

// Service Worker Registration (for PWA capabilities)
if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker.register('./sw.js')
            .then(registration => {
                console.log('SW registered: ', registration);
            })
            .catch(registrationError => {
                console.log('SW registration failed: ', registrationError);
            });
    });
}
