// Language selector with dropdown functionality for menu interface
class LanguageSelector {
    constructor() {
        this.currentLanguage = localStorage.getItem('menu_language') || 'mk';
        this.allLanguages = [
            { code: 'mk', name: 'Македонски', flag: '🇲🇰', nativeName: 'Македонски' },
            { code: 'en', name: 'English', flag: '🇬🇧', nativeName: 'English' },
            { code: 'al', name: 'Shqip', flag: '🇦🇱', nativeName: 'Shqip' }
        ];
        this.languages = []; // Will be filtered based on restaurant settings
        this.restaurantSlug = window.restaurantSlug;
    }
    
    async init() {
        // Fetch restaurant data to get supported languages
        if (this.restaurantSlug) {
            try {
                const response = await axios.get(`/api/restaurants/slug/${this.restaurantSlug}`);
                if (response.data.success && response.data.data.supported_languages) {
                    const supportedLanguages = response.data.data.supported_languages;
                    // Filter to only show supported languages
                    this.languages = this.allLanguages.filter(lang => 
                        supportedLanguages.includes(lang.code)
                    );
                } else {
                    // Default to all languages if not specified
                    this.languages = this.allLanguages;
                }
            } catch (error) {
                console.error('Error fetching restaurant languages:', error);
                // Fallback to all languages
                this.languages = this.allLanguages;
            }
        } else {
            // Default to all languages
            this.languages = this.allLanguages;
        }
        
        // Only render if there are languages to show
        if (this.languages.length > 0) {
            this.render('language-selector');
            this.renderMobile('mobile-lang-container');
        }
    }
    
    getCurrentLanguageData() {
        return this.languages.find(lang => lang.code === this.currentLanguage) || this.languages[0];
    }
    
    render(containerId) {
        const container = document.getElementById(containerId);
        if (!container) return;
        
        // Don't render if only one language is available
        if (this.languages.length <= 1) {
            container.innerHTML = '';
            return;
        }
        
        const currentLang = this.getCurrentLanguageData();
        
        container.innerHTML = `
            <div class="relative language-dropdown-container z-[9999]">
                <button onclick="toggleLanguageDropdown()" 
                        class="flex items-center gap-2 px-3 py-2 bg-white rounded-lg border border-gray-300 hover:border-brand-orange transition-all shadow-sm"
                        aria-label="Select language"
                        aria-haspopup="true"
                        aria-expanded="false"
                        id="language-dropdown-button">
                    <span class="text-xl">${currentLang.flag}</span>
                    <span class="text-sm font-medium text-gray-700 hidden sm:inline">${currentLang.code.toUpperCase()}</span>
                    <svg class="w-4 h-4 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                    </svg>
                </button>
                
                <!-- Dropdown menu -->
                <div id="language-dropdown-menu" 
                     class="hidden absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 language-dropdown z-[9999]"
                     role="menu"
                     aria-orientation="vertical"
                     aria-labelledby="language-dropdown-button">
                    ${this.languages.map((lang, index) => `
                        <button onclick="changeMenuLanguage('${lang.code}')" 
                                class="w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-gray-50 transition-colors language-option ${lang.code === this.currentLanguage ? 'selected' : ''} ${index === 0 ? 'rounded-t-lg' : ''} ${index === this.languages.length - 1 ? 'rounded-b-lg' : ''}"
                                role="menuitem"
                                tabindex="${index === 0 ? '0' : '-1'}">
                            <span class="text-2xl">${lang.flag}</span>
                            <div class="flex-1">
                                <div class="font-medium text-gray-900">${lang.nativeName}</div>
                                <div class="text-xs text-gray-500">${lang.name}</div>
                            </div>
                            ${lang.code === this.currentLanguage ? `
                                <svg class="w-5 h-5 text-brand-orange" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"></path>
                                </svg>
                            ` : ''}
                        </button>
                    `).join('')}
                </div>
            </div>
        `;
    }
    
    renderMobile(containerId) {
        const container = document.getElementById(containerId);
        if (!container) return;
        
        // Don't render if only one language is available
        if (this.languages.length <= 1) {
            container.innerHTML = '';
            return;
        }
        
        container.innerHTML = `
            <div class="w-full">
                <label class="block text-xs font-medium text-gray-500 mb-2">Language</label>
                <div class="grid grid-cols-3 gap-2">
                    ${this.languages.map(lang => `
                        <button onclick="changeMenuLanguage('${lang.code}')" 
                                class="flex flex-col items-center gap-1 px-3 py-2 rounded-md transition-all mobile-language-option ${lang.code === this.currentLanguage ? 'selected ring-2 ring-brand-orange bg-orange-50' : 'bg-gray-50 hover:bg-gray-100'}" 
                                title="${lang.name}">
                            <span class="text-2xl">${lang.flag}</span>
                            <span class="text-xs font-medium ${lang.code === this.currentLanguage ? 'text-brand-orange' : 'text-gray-600'}">${lang.code.toUpperCase()}</span>
                        </button>
                    `).join('')}
                </div>
            </div>
        `;
    }
}

// Global function to toggle dropdown
function toggleLanguageDropdown() {
    const dropdown = document.getElementById('language-dropdown-menu');
    const button = document.getElementById('language-dropdown-button');
    
    if (!dropdown || !button) return;
    
    const isHidden = dropdown.classList.contains('hidden');
    
    if (isHidden) {
        dropdown.classList.remove('hidden');
        button.setAttribute('aria-expanded', 'true');
        
        // Focus first menu item
        const firstItem = dropdown.querySelector('.language-option');
        if (firstItem) {
            setTimeout(() => firstItem.focus(), 10);
        }
    } else {
        dropdown.classList.add('hidden');
        button.setAttribute('aria-expanded', 'false');
    }
}

// Global function to change language
function changeMenuLanguage(language) {
    localStorage.setItem('menu_language', language);
    
    // Hide dropdown
    const dropdown = document.getElementById('language-dropdown-menu');
    if (dropdown) {
        dropdown.classList.add('hidden');
    }
    
    // Update the button to show selected language
    if (window.languageSelectorInstance) {
        window.languageSelectorInstance.currentLanguage = language;
        window.languageSelectorInstance.render('language-selector');
    }
    
    // If MenuApp exists, use its changeLanguage method
    if (window.app && typeof window.app.changeLanguage === 'function') {
        window.app.changeLanguage(language);
    } else {
        // Fallback - reload the page
        window.location.reload();
    }
}

// Close dropdown when clicking outside
document.addEventListener('click', function(event) {
    const dropdownContainer = document.querySelector('.language-dropdown-container');
    const dropdown = document.getElementById('language-dropdown-menu');
    const button = document.getElementById('language-dropdown-button');
    
    if (dropdownContainer && dropdown && button && 
        !dropdownContainer.contains(event.target)) {
        dropdown.classList.add('hidden');
        button.setAttribute('aria-expanded', 'false');
    }
});

// Handle keyboard navigation in dropdown
document.addEventListener('keydown', function(event) {
    const dropdown = document.getElementById('language-dropdown-menu');
    const button = document.getElementById('language-dropdown-button');
    
    if (!dropdown || dropdown.classList.contains('hidden')) return;
    
    const options = Array.from(dropdown.querySelectorAll('.language-option'));
    const currentIndex = options.findIndex(option => option === document.activeElement);
    
    switch(event.key) {
        case 'Escape':
            dropdown.classList.add('hidden');
            button.setAttribute('aria-expanded', 'false');
            button.focus();
            event.preventDefault();
            break;
        case 'ArrowDown':
            if (currentIndex < options.length - 1) {
                options[currentIndex + 1].focus();
            }
            event.preventDefault();
            break;
        case 'ArrowUp':
            if (currentIndex > 0) {
                options[currentIndex - 1].focus();
            } else if (currentIndex === 0) {
                button.focus();
                dropdown.classList.add('hidden');
                button.setAttribute('aria-expanded', 'false');
            }
            event.preventDefault();
            break;
        case 'Home':
            options[0].focus();
            event.preventDefault();
            break;
        case 'End':
            options[options.length - 1].focus();
            event.preventDefault();
            break;
    }
});

// Initialize language selector when DOM is loaded
document.addEventListener('DOMContentLoaded', async function() {
    const languageSelector = new LanguageSelector();
    
    // Store instance globally so changeMenuLanguage can access it
    window.languageSelectorInstance = languageSelector;
    
    // Initialize and render language selector (will fetch supported languages first)
    await languageSelector.init();
});
