/**
 * Intelligent Translation System for Xtreme Code
 * Auto-detects browser language and provides seamless translation
 */

(function() {
    'use strict';

    // Supported languages with flags
    const languages = {
        'en': { name: 'English', flag: '🇬🇧', code: 'en' },
        'it': { name: 'Italiano', flag: '🇮🇹', code: 'it' },
        'es': { name: 'Español', flag: '🇪🇸', code: 'es' },
        'fr': { name: 'Français', flag: '🇫🇷', code: 'fr' }
    };

    let currentLang = 'en';
    let translations = {};

    // Get saved language or detect from browser
    function getInitialLanguage() {
        const saved = localStorage.getItem('xtreme_code_lang');
        if (saved && languages[saved]) {
            return saved;
        }
        
        // Auto-detect browser language, but default to English
        const browserLang = (navigator.language || navigator.userLanguage).split('-')[0].toLowerCase();
        // Only auto-translate if browser language is supported and not English
        if (browserLang !== 'en' && languages[browserLang]) {
            return browserLang;
        }
        
        return 'en'; // Default to English
    }

    // Load translations from JSON file
    async function loadTranslations(lang) {
        // English is the default, no translation needed
        if (lang === 'en') {
            translations[lang] = {};
            return {};
        }

        if (translations[lang]) {
            return translations[lang];
        }

        try {
            // Try to get translations path from WordPress
            let translationsPath = window.xtremeCodeTranslationsPath || '/wp-content/plugins/stock-guardian-pro/assets/translations/';
            
            // Ensure path ends with /
            if (!translationsPath.endsWith('/')) {
                translationsPath += '/';
            }
            
            // Build URL
            let url;
            if (translationsPath.startsWith('http://') || translationsPath.startsWith('https://')) {
                // Full URL
                url = `${translationsPath}${lang}.json`;
            } else {
                // Relative path - remove leading slash if present
                const cleanPath = translationsPath.startsWith('/') ? translationsPath.substring(1) : translationsPath;
                url = `${window.location.origin}/${cleanPath}${lang}.json`;
            }
            
            console.log('Loading translations from:', url);
            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json'
                }
            });
            
            if (response.ok) {
                translations[lang] = await response.json();
                console.log('Translations loaded successfully for:', lang, Object.keys(translations[lang]).length, 'keys');
                return translations[lang];
            } else {
                console.warn('Translation file not found or error:', url, 'Status:', response.status, response.statusText);
            }
        } catch (error) {
            console.error('Error loading translation file for:', lang, error);
        }
        
        return {};
    }

    // Translate text
    function translateText(text, lang) {
        if (lang === 'en') {
            return text; // English is the default
        }
        
        const langTranslations = translations[lang] || {};
        const translated = langTranslations[text];
        
        if (translated) {
            return translated;
        }
        
        // If translation not found, return original
        return text;
    }

    // Translate all elements with data-translate attribute
    function translatePage(lang) {
        console.log('Translating page to:', lang);
        
        const elements = document.querySelectorAll('[data-translate]');
        let translatedCount = 0;
        let notFoundCount = 0;
        
        console.log('Found', elements.length, 'elements with data-translate attribute');
        
        // First, restore original text for all elements (if switching from another language)
        elements.forEach(element => {
            // Save original text if not already saved (first time)
            if (!element.hasAttribute('data-original')) {
                const originalText = element.textContent.trim();
                element.setAttribute('data-original', originalText);
            } else {
                // Restore original text before applying new translation
                const originalText = element.getAttribute('data-original');
                if (originalText) {
                    element.textContent = originalText;
                }
            }
        });
        
        // If English, we're done (original text is already restored)
        if (lang === 'en') {
            console.log('Language set to English, original text restored for', elements.length, 'elements');
            updateLanguageSwitcher(lang);
            localStorage.setItem('xtreme_code_lang', lang);
            currentLang = lang;
            document.documentElement.lang = lang;
            return;
        }
        
        // Translate to selected language
        elements.forEach(element => {
            const key = element.getAttribute('data-translate');
            if (!key) {
                console.warn('Element has data-translate attribute but no value:', element);
                notFoundCount++;
                return;
            }
            
            const translated = translateText(key, lang);
            if (translated && translated !== key) {
                // Clear any child elements and set translated text
                element.innerHTML = '';
                element.textContent = translated;
                translatedCount++;
                if (translatedCount <= 5) { // Log first 5 for debugging
                    console.log('Translated:', key, '->', translated);
                }
            } else {
                // Translation not found
                notFoundCount++;
                if (notFoundCount <= 5) { // Log first 5 for debugging
                    console.warn('Translation not found for key:', key, 'in language:', lang);
                }
            }
        });
        
        console.log('Translation complete. Translated:', translatedCount, 'Not found:', notFoundCount, 'Total:', elements.length);

        // Translate attributes
        const attrElements = document.querySelectorAll('[data-translate-attr]');
        attrElements.forEach(element => {
            const attrData = element.getAttribute('data-translate-attr');
            if (attrData) {
                const [attr, key] = attrData.split(':');
                const translated = translateText(key, lang);
                if (translated && translated !== key) {
                    element.setAttribute(attr, translated);
                }
            }
        });

        // Update language switcher
        updateLanguageSwitcher(lang);
        
        // Save preference
        localStorage.setItem('xtreme_code_lang', lang);
        currentLang = lang;
        
        // Update HTML lang attribute
        document.documentElement.lang = lang;
    }

    // Create language switcher
    function createLanguageSwitcher() {
        const switcher = document.createElement('div');
        switcher.className = 'xtreme-lang-switcher';
        switcher.innerHTML = `
            <button class="xtreme-lang-button" aria-label="Select Language">
                <span class="xtreme-lang-flag">${languages[currentLang].flag}</span>
                <span class="xtreme-lang-code">${languages[currentLang].code.toUpperCase()}</span>
            </button>
            <div class="xtreme-lang-dropdown">
                ${Object.keys(languages).map(lang => `
                    <button class="xtreme-lang-option ${lang === currentLang ? 'active' : ''}" data-lang="${lang}">
                        <span class="xtreme-lang-flag">${languages[lang].flag}</span>
                        <span class="xtreme-lang-name">${languages[lang].name}</span>
                    </button>
                `).join('')}
            </div>
        `;
        document.body.appendChild(switcher);

        // Toggle dropdown
        const button = switcher.querySelector('.xtreme-lang-button');
        const dropdown = switcher.querySelector('.xtreme-lang-dropdown');
        
        button.addEventListener('click', (e) => {
            e.stopPropagation();
            dropdown.classList.toggle('active');
        });

        // Select language
        switcher.querySelectorAll('.xtreme-lang-option').forEach(option => {
            option.addEventListener('click', (e) => {
                e.stopPropagation();
                const lang = option.getAttribute('data-lang');
                changeLanguage(lang);
                dropdown.classList.remove('active');
            });
        });

        // Close on outside click
        document.addEventListener('click', () => {
            dropdown.classList.remove('active');
        });
    }

    // Update language switcher
    function updateLanguageSwitcher(lang) {
        const button = document.querySelector('.xtreme-lang-button');
        const flag = document.querySelector('.xtreme-lang-flag');
        const code = document.querySelector('.xtreme-lang-code');
        
        if (button && flag && code) {
            flag.textContent = languages[lang].flag;
            code.textContent = languages[lang].code.toUpperCase();
        }

        // Update active state
        document.querySelectorAll('.xtreme-lang-option').forEach(option => {
            option.classList.toggle('active', option.getAttribute('data-lang') === lang);
        });
    }

    // Change language
    async function changeLanguage(lang) {
        if (!languages[lang]) {
            console.warn('Language not supported:', lang);
            return;
        }
        
        console.log('Changing language to:', lang);
        
        // Load translations if not English
        if (lang !== 'en') {
            await loadTranslations(lang);
        }
        
        // Translate the page
        translatePage(lang);
        
        console.log('Language changed successfully to:', lang);
    }

    // Initialize
    async function init() {
        currentLang = getInitialLanguage();
        console.log('Initial language detected:', currentLang);
        
        // Load translations if not English
        if (currentLang !== 'en') {
            await loadTranslations(currentLang);
        }
        
        // Create switcher first so it shows the correct flag
        createLanguageSwitcher();
        
        // Then translate if needed
        if (currentLang !== 'en') {
            translatePage(currentLang);
        }
    }

    // Start when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

    // Export for external use
    window.XtremeCodeTranslator = {
        changeLanguage,
        getCurrentLanguage: () => currentLang,
        getSupportedLanguages: () => Object.keys(languages)
    };

})();

