document.addEventListener('DOMContentLoaded', function() {
    // Menu functionality
    const menuToggle = document.querySelector('.menu-toggle');
    const menuContainer = document.querySelector('.menu-container');
    const body = document.body;
    
    // Only add menu functionality if menu elements exist
    if (menuToggle && menuContainer) {
        // Enhanced menu toggle with better accessibility
        menuToggle.addEventListener('click', function() {
            const isActive = menuToggle.classList.contains('active');
            
            menuToggle.classList.toggle('active');
            menuContainer.classList.toggle('active');

            // Toggle theme switcher visibility based on menu active state
            const themeSwitcher = document.querySelector('.theme-switcher');
            if (themeSwitcher) {
                if (menuContainer.classList.contains('active')) {
                    themeSwitcher.classList.add('hidden');
                } else {
                    themeSwitcher.classList.remove('hidden');
                }
            }
            
            // Update ARIA attributes for accessibility
            menuToggle.setAttribute('aria-expanded', !isActive);
            
            // Prevent body scroll when menu is open
            if (!isActive) {
                body.style.overflow = 'hidden';
            } else {
                body.style.overflow = '';
            }
        });
        
        // Close menu when clicking menu items
        document.querySelectorAll('.menu li a').forEach(item => {
            item.addEventListener('click', function() {
                menuToggle.classList.remove('active');
                menuContainer.classList.remove('active');
                menuToggle.setAttribute('aria-expanded', 'false');
                body.style.overflow = '';
            });
        });
        
        // Close menu when clicking outside
        document.addEventListener('click', function(event) {
            const isClickInsideMenu = menuContainer.contains(event.target);
            const isClickOnToggle = menuToggle.contains(event.target);
            
            if (!isClickInsideMenu && !isClickOnToggle && menuContainer.classList.contains('active')) {
                menuToggle.classList.remove('active');
                menuContainer.classList.remove('active');
                const themeSwitcher = document.querySelector('.theme-switcher');
                if (themeSwitcher) {
                    themeSwitcher.classList.remove('hidden');
                }
                menuToggle.setAttribute('aria-expanded', 'false');
                body.style.overflow = '';
            }
        });
        
        // Keyboard navigation support
        document.addEventListener('keydown', function(event) {
            // Close menu with Escape key
            if (event.key === 'Escape' && menuContainer.classList.contains('active')) {
                menuToggle.classList.remove('active');
                menuContainer.classList.remove('active');
                const themeSwitcher = document.querySelector('.theme-switcher');
                if (themeSwitcher) {
                    themeSwitcher.classList.remove('hidden');
                }
                menuToggle.setAttribute('aria-expanded', 'false');
                body.style.overflow = '';
                menuToggle.focus();
            }
        });
        
        // Initialize ARIA attributes
        menuToggle.setAttribute('aria-expanded', 'false');
        menuToggle.setAttribute('aria-controls', 'menu-container');
        menuContainer.setAttribute('id', 'menu-container');
    }
    
    // Smooth scroll for anchor links
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    });
    
    // Add fade-in animation to elements when they come into view
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };
    
    const observer = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('fade-in');
                observer.unobserve(entry.target);
            }
        });
    }, observerOptions);
    
    // Observe all elements with fade-in class
    document.querySelectorAll('.fade-in').forEach(el => {
        observer.observe(el);
    });
    
    // Simple download button interactions
    document.querySelectorAll('.download-button').forEach(button => {
        button.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-4px)';
        });
        
        button.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
        });
    });
    
    // Mobile touch improvements
    if ('ontouchstart' in window) {
        // Add touch-friendly hover states
        document.querySelectorAll('.menu li a, .download-button').forEach(element => {
            element.addEventListener('touchstart', function() {
                this.classList.add('touch-active');
            });
            
            element.addEventListener('touchend', function() {
                setTimeout(() => {
                    this.classList.remove('touch-active');
                }, 100);
            });
        });
        
        // Add touch-active styles
        const touchStyle = document.createElement('style');
        touchStyle.innerHTML = `
            .touch-active {
                transform: scale(0.98) !important;
                opacity: 0.9 !important;
            }
        `;
        document.head.appendChild(touchStyle);
    }
    
    
    // Theme Switcher Functionality
    const themeSteps = document.querySelectorAll('.theme-step');
    const themeSwitcher = document.querySelector('.theme-switcher');
    const themeIndicator = document.querySelector('.theme-indicator');
    
    // Valid themes (4 colors only)
    const validThemes = ['default', 'blue', 'purple', 'green'];
    
    // Load saved theme or default
    let savedTheme = localStorage.getItem('liguana-theme') || 'default';
    
    // Check if saved theme is valid, if not reset to default
    if (!validThemes.includes(savedTheme)) {
        savedTheme = 'default';
        localStorage.setItem('liguana-theme', savedTheme);
    }
    
    setTheme(savedTheme);
    
    // Theme switcher event listeners
    themeSteps.forEach(step => {
        step.addEventListener('click', function() {
            const theme = this.getAttribute('data-theme');
            if (validThemes.includes(theme)) {
                setTheme(theme);
                localStorage.setItem('liguana-theme', theme);
            }
        });
    });
    
    // Theme preview event listeners
    const themePreviews = document.querySelectorAll('.theme-preview');
    themePreviews.forEach(preview => {
        preview.addEventListener('click', function() {
            const theme = this.getAttribute('data-theme');
            if (validThemes.includes(theme)) {
                setTheme(theme);
                localStorage.setItem('liguana-theme', theme);
            }
        });
    });
    
    // Add click event to theme indicator for cycling through themes
    if (themeIndicator) {
        themeIndicator.addEventListener('click', function() {
            // Get current theme index
            const currentTheme = localStorage.getItem('liguana-theme') || 'default';
            const currentIndex = validThemes.indexOf(currentTheme);
            
            // Calculate next theme index (cycle back to first after last)
            const nextIndex = (currentIndex + 1) % validThemes.length;
            const nextTheme = validThemes[nextIndex];
            
            // Apply next theme
            setTheme(nextTheme);
            localStorage.setItem('liguana-theme', nextTheme);
        });
    }
    
    function setTheme(theme) {
        // Ensure theme is valid
        if (!validThemes.includes(theme)) {
            theme = 'default';
        }
        
        // Update switcher active state
        if (themeSwitcher) {
            themeSwitcher.setAttribute('data-active', theme);
        }
        
        // Apply theme to body
        if (theme === 'default') {
            body.removeAttribute('data-theme');
        } else {
            body.setAttribute('data-theme', theme);
        }
    }
    
    // Initialize ARIA attributes
    menuToggle.setAttribute('aria-expanded', 'false');
    menuToggle.setAttribute('aria-controls', 'menu-container');
    menuContainer.setAttribute('id', 'menu-container');
    
    // Add loading state management
    window.addEventListener('load', function() {
        document.body.classList.add('loaded');
        
        // Trigger fade-in animations for initially visible elements
        document.querySelectorAll('.fade-in').forEach(el => {
            const rect = el.getBoundingClientRect();
            if (rect.top < window.innerHeight && rect.bottom > 0) {
                el.classList.add('fade-in');
            }
        });
    });
    
    console.log('🦎 Lingoano - Sade tasarım ve tema değiştirici yüklendi!');
});

// Donate Button Functionality
document.addEventListener('DOMContentLoaded', function() {
    const donateButton = document.querySelector('.donate-button');
    const donatePopup = document.querySelector('.donate-popup');
    const donateClose = document.querySelector('.donate-close');
    
    if (donateButton && donatePopup && donateClose) {
        donateButton.addEventListener('click', function() {
            donatePopup.classList.add('active');
        });
        
        donateClose.addEventListener('click', function() {
            donatePopup.classList.remove('active');
        });
        
        donatePopup.addEventListener('click', function(event) {
            if (event.target === donatePopup) {
                donatePopup.classList.remove('active');
            }
        });
    }
});



// Language Learning Matching System
let matchingSocket = null;
let isMatching = false;

// Initialize matching system when form is submitted
document.addEventListener('DOMContentLoaded', function() {
    const languageForm = document.getElementById('language-form');
    
    if (languageForm) {
        languageForm.addEventListener('submit', function (e) {
            e.preventDefault();

            const language = document.getElementById('language').value;
            const level = document.getElementById('level').value;

            if (language && level) {
                console.log("Seçilen Dil:", language);
                console.log("Seviye:", level);
                
                // Persist baseline language for other pages (puzzle, word-of-day)
                try {
                    localStorage.setItem('liguana-language', language);
                    localStorage.setItem('liguana-level', level);
                } catch (e) {}

                startMatching(language, level);
            } else {
                const lm = window.languageManager;
                const msg = lm && typeof lm.getText === 'function'
                    ? (lm.getText('select-language-level') || 'Lütfen dil ve seviye seçiniz.')
                    : 'Lütfen dil ve seviye seçiniz.';
                alert(msg);
            }
        });
    }
});

// Mesaj kutusu gösterme fonksiyonu
function showNotification(message, type = 'info', duration = 3000) {
    // Mevcut bildirimleri temizle
    const existingNotifications = document.querySelectorAll('.notification');
    existingNotifications.forEach(notification => notification.remove());
    
    // Yeni bildirim oluştur
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = message;
    
    // Stil ekle
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        background-color: ${type === 'success' ? '#4CAF50' : type === 'error' ? '#f44336' : '#2196F3'};
        color: white;
        padding: 15px 25px;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        z-index: 10000;
        font-size: 16px;
        font-weight: 500;
        max-width: 400px;
        text-align: center;
        animation: slideDown 0.3s ease-out;
    `;
    
    // Animasyon CSS'i ekle
    if (!document.querySelector('#notification-styles')) {
        const style = document.createElement('style');
        style.id = 'notification-styles';
        style.innerHTML = `
            @keyframes slideDown {
                from {
                    opacity: 0;
                    transform: translateX(-50%) translateY(-20px);
                }
                to {
                    opacity: 1;
                    transform: translateX(-50%) translateY(0);
                }
            }
            @keyframes slideUp {
                from {
                    opacity: 1;
                    transform: translateX(-50%) translateY(0);
                }
                to {
                    opacity: 0;
                    transform: translateX(-50%) translateY(-20px);
                }
            }
        `;
        document.head.appendChild(style);
    }
    
    // Sayfaya ekle
    document.body.appendChild(notification);
    
    // Belirtilen süre sonra kaldır
    if (duration > 0) {
        setTimeout(() => {
            notification.style.animation = 'slideUp 0.3s ease-out';
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.remove();
                }
            }, 300);
        }, duration);
    }
    
    return notification;
}

// Legacy local translations removed; use global languageManager/translations.js


function startMatching(language, level) {
    if (isMatching) return;
    
    isMatching = true;

    // Eşleşme araması başladığına dair bildirim göster
    const lm = window.languageManager;
    // Sync UI language with current site selector before showing texts
    try {
        const siteSel = document.getElementById('site-language') || document.getElementById('site-language-desktop');
        const uiLang = siteSel && siteSel.value ? siteSel.value : null;
        if (lm && typeof lm.setLanguage === 'function' && uiLang) {
            lm.setLanguage(uiLang, true);
        }
    } catch (e) {}
    const t = (key, fallback) => (lm && typeof lm.getText === 'function' && lm.getText(key)) || fallback || key;
    showNotification(t('matching-search-started', '🔍 Eşleşme araması başlatıldı! Size uygun bir partner aranıyor...'), 'info', 4000);
    // Show loading state
    const submitButton = document.querySelector('#language-form button[type="submit"]');
    const originalText = submitButton.innerHTML;
    submitButton.innerHTML = t('searching-match-button', 'Eşleşme aranıyor...');
    submitButton.disabled = true;
    
    // Connect to matching server
    try {
        matchingSocket = new WebSocket('wss://lingoano.onrender.com/liguanadinlemeserver/match');
        
        matchingSocket.onopen = function() {
            console.log('Matching server connected');
            // Send language and level for matching
            matchingSocket.send(JSON.stringify({
                language: language,
                level: level
            }));
        };
        
        matchingSocket.onmessage = function(event) {
            const data = JSON.parse(event.data);
            console.log('Matching response:', data);
            
            switch(data.status) {
                case 'waiting':
                    submitButton.innerHTML = t('waiting-match-button', 'Eşleşme bekleniyor...');
                    showNotification(t('matching-waiting', '⏳ Eşleşme bekleniyor... Başka bir kullanıcı aranıyor.'), 'info', 0);
                    console.log('Waiting for match:', data.message);
                    break;
                    
                case 'matched':
                    console.log('Match found! Topic:', data.topic);
                    submitButton.innerHTML = t('matched-redirecting-button', 'Eşleşme bulundu! Yönlendiriliyor...');
                    showNotification(t('matching-found-notification', '🎉 Eşleşme bulundu! Sohbet sayfasına yönlendiriliyorsunuz...'), 'success', 2000);
                    
                    // Store topic for chat page (align with chat.html expected keys)
                    try {
                        sessionStorage.setItem('Lingoano_topic', data.topic);
                        sessionStorage.setItem('Lingoano_role', data.role);
                        sessionStorage.setItem('Lingoano_language', language);
                        sessionStorage.setItem('Lingoano_level', level);
                        // Backward-compat: also write legacy keys
                        sessionStorage.setItem('liguana_topic', data.topic);
                        sessionStorage.setItem('liguana_role', data.role);
                        sessionStorage.setItem('liguana_language', language);
                        sessionStorage.setItem('liguana_level', level);
                    } catch (e) {}
                    
                    // Redirect to chat page after short delay
                    setTimeout(() => {
                        window.location.href = 'chat.html';
                    }, 1500);
                    break;
                    
                case 'error':
                    console.error('Matching error:', data.message);
                    showNotification((t('matching-error', '❌ Eşleşme hatası')) + ': ' + (data.message || ''), 'error', 5000);
                    resetMatchingState(submitButton, originalText);
                    break;
                    
                case 'peer_disconnected':
                    console.log('Peer disconnected:', data.message);
                    showNotification(t('peer-disconnected-notification', '⚠️ Eşleşen kullanıcı bağlantıyı kesti. Tekrar deneyin.'), 'error', 5000);
                    resetMatchingState(submitButton, originalText);
                    break;
            }
        };
        
        matchingSocket.onerror = function(error) {
            console.error('Matching socket error:', error);
            showNotification(t('server-connection-failed', '🔌 Sunucuya bağlanılamadı. Lütfen sunucunun çalıştığından emin olun.'), 'error', 5000);
            resetMatchingState(submitButton, originalText);
        };
        
        matchingSocket.onclose = function() {
            console.log('Matching socket closed');
            if (isMatching) {
                resetMatchingState(submitButton, originalText);
            }
        };
        
    } catch (error) {
        console.error('Failed to connect to matching server:', error);
        showNotification('🔌 Sunucuya bağlanılamadı. Lütfen tekrar deneyin.', 'error', 5000);
        resetMatchingState(submitButton, originalText);
    }
}

function resetMatchingState(button, originalText) {
    isMatching = false;
    button.innerHTML = originalText;
    button.disabled = false;
    
    if (matchingSocket) {
        matchingSocket.close();
        matchingSocket = null;
    }
}

// Handle page unload - disconnect from matching if still connecting
window.addEventListener('beforeunload', function() {
    if (matchingSocket && isMatching) {
        matchingSocket.close();
    }
});
