// Dark Mode & Theme Functionality
document.addEventListener('DOMContentLoaded', function() {
    'use strict';

    let longPressTimer;
    let themePopup;

    // Check for saved preferences and apply immediately
    const isDarkMode = localStorage.getItem('darkMode') === 'true';
    const savedTheme = localStorage.getItem('theme') || 'green';

    if (isDarkMode) {
        document.body.classList.add('dark-mode');
    }
    document.body.setAttribute('data-theme', savedTheme);

    // Create theme selector popup
    function createThemePopup() {
        const popup = document.createElement('div');
        popup.className = 'theme-selector-popup';
        popup.innerHTML = `
            <h4>🎨 Select Theme</h4>
            <div class="theme-options">
                <div class="theme-option" data-theme="green">
                    <div class="theme-color-preview green"></div>
                    <span>Green</span>
                </div>
                <div class="theme-option" data-theme="pink">
                    <div class="theme-color-preview pink"></div>
                    <span>Pink</span>
                </div>
                <div class="theme-option" data-theme="blue">
                    <div class="theme-color-preview blue"></div>
                    <span>Blue</span>
                </div>
                <div class="theme-option" data-theme="red">
                    <div class="theme-color-preview red"></div>
                    <span>Red</span>
                </div>
            </div>
        `;
        document.body.appendChild(popup);

        // Add click handlers for theme options
        popup.querySelectorAll('.theme-option').forEach(option => {
            option.addEventListener('click', function() {
                const theme = this.getAttribute('data-theme');
                setTheme(theme);
                hideThemePopup();
            });
        });

        // Close popup when clicking outside
        document.addEventListener('click', function closePopupHandler(e) {
            // Don't close if clicking on the popup itself or the toggle button
            if (popup.contains(e.target) || e.target.closest('.dark-mode-toggle')) {
                return;
            }
            hideThemePopup();
        });

        return popup;
    }

    // Create dark mode toggle button
    function createDarkModeToggle() {
        // Check if button already exists
        if (document.querySelector('.dark-mode-toggle')) {
            return;
        }

        const toggleButton = document.createElement('button');
        toggleButton.className = 'dark-mode-toggle';
        toggleButton.setAttribute('aria-label', 'Toggle Dark Mode');
        toggleButton.setAttribute('title', 'Click to toggle Dark/Light Mode. Long press (mobile) or right-click (desktop) to select theme');
        toggleButton.innerHTML = `
            <span class="moon-icon">🌙</span>
            <span class="sun-icon">☀️</span>
        `;

        // Regular click - toggle dark mode
        toggleButton.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();

            // Don't toggle if popup is open
            if (themePopup && themePopup.classList.contains('active')) {
                return;
            }

            toggleDarkMode();
        });

        // Desktop - Right-click to show theme selector
        toggleButton.addEventListener('contextmenu', function(e) {
            console.log('Right-click detected');
            e.preventDefault();
            e.stopPropagation();
            showThemePopup();
        });

        // Mobile - Long press to show theme selector
        toggleButton.addEventListener('touchstart', function(e) {
            toggleButton.classList.add('long-pressing');
            longPressTimer = setTimeout(() => {
                showThemePopup();
                toggleButton.classList.remove('long-pressing');
            }, 500); // 500ms long press
        });

        toggleButton.addEventListener('touchend', function(e) {
            clearTimeout(longPressTimer);
            toggleButton.classList.remove('long-pressing');
        });

        toggleButton.addEventListener('touchcancel', function(e) {
            clearTimeout(longPressTimer);
            toggleButton.classList.remove('long-pressing');
        });

        document.body.appendChild(toggleButton);
    }

    // Toggle dark mode
    function toggleDarkMode() {
        const body = document.body;
        const isDark = body.classList.toggle('dark-mode');

        // Save preference to localStorage
        localStorage.setItem('darkMode', isDark);

        // Add animation effect
        body.style.transition = 'all 0.3s ease';
    }

    // Set theme
    function setTheme(theme) {
        document.body.setAttribute('data-theme', theme);
        localStorage.setItem('theme', theme);

        // Update active state in popup
        if (themePopup) {
            themePopup.querySelectorAll('.theme-option').forEach(opt => {
                opt.classList.remove('active');
            });
            themePopup.querySelector(`[data-theme="${theme}"]`).classList.add('active');
        }

        // Emit theme change event for pet system
        window.dispatchEvent(new CustomEvent('themeChanged', { detail: { theme } }));
    }

    // Show theme popup
    function showThemePopup() {
        if (!themePopup) {
            themePopup = createThemePopup();
        }

        // Update active theme
        const currentTheme = localStorage.getItem('theme') || 'green';
        themePopup.querySelectorAll('.theme-option').forEach(opt => {
            opt.classList.remove('active');
        });
        const activeOption = themePopup.querySelector(`[data-theme="${currentTheme}"]`);
        if (activeOption) {
            activeOption.classList.add('active');
        }

        themePopup.classList.add('active');
        console.log('Theme popup shown');
    }

    // Hide theme popup
    function hideThemePopup() {
        if (themePopup) {
            themePopup.classList.remove('active');
        }
    }

    // Create mini game button (only for students)
    function createMiniGameButton() {
        // Check if button already exists
        if (document.querySelector('.mini-game-toggle')) {
            return;
        }

        // Only show mini game button for students, not instructors
        const isInstructor = window.location.pathname.includes('/instructor/');
        if (isInstructor) {
            return;
        }

        const gameButton = document.createElement('a');
        gameButton.href = window.location.pathname.includes('/student/') ? 'code_challenges.php' : '../student/code_challenges.php';
        gameButton.className = 'mini-game-toggle';
        gameButton.setAttribute('aria-label', 'Code Challenges Mini Game');
        gameButton.setAttribute('title', 'Play Code Challenges');
        gameButton.innerHTML = '🎮';

        document.body.appendChild(gameButton);
    }

    // Create the toggle button
    createDarkModeToggle();
    // Create mini game button
    createMiniGameButton();
});
