/**
 * Google Translate Integration
 * Automatically translates page content when language is selected
 * SAFE VERSION - Won't block page loading
 */

(function() {
    'use strict';

    let googleTranslateLoaded = false;
    let translateElement = null;
    let initAttempted = false;

    /**
     * Language code mapping to Google Translate codes
     */
    const languageCodes = {
        'it': 'it',  // Italian
        'en': 'en',  // English
        'es': 'es',  // Spanish
        'de': 'de'   // German
    };

    /**
     * Initialize Google Translate (SAFE - won't block)
     */
    function initGoogleTranslate() {
        if (googleTranslateLoaded || initAttempted) return;
        initAttempted = true;

        try {
            // Create hidden Google Translate element
            const translateDiv = document.createElement('div');
            translateDiv.id = 'google_translate_element';
            translateDiv.style.display = 'none';
            translateDiv.style.position = 'absolute';
            translateDiv.style.left = '-9999px';
            translateDiv.style.width = '1px';
            translateDiv.style.height = '1px';
            translateDiv.style.overflow = 'hidden';
            document.body.appendChild(translateDiv);

            // Load Google Translate script asynchronously
            const script = document.createElement('script');
            script.type = 'text/javascript';
            script.async = true;
            script.defer = true;
            script.src = 'https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit';
            script.onerror = function() {
                console.warn('Google Translate script failed to load - using fallback');
                googleTranslateLoaded = false;
            };
            document.head.appendChild(script);

            // Initialize function (must be global)
            window.googleTranslateElementInit = function() {
                try {
                    if (window.google && window.google.translate) {
                        translateElement = new google.translate.TranslateElement({
                            pageLanguage: 'en',
                            includedLanguages: 'it,en,es,de',
                            layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
                            autoDisplay: false
                        }, 'google_translate_element');
                        googleTranslateLoaded = true;
                        console.log('✅ Google Translate initialized');
                    }
                } catch (e) {
                    console.error('Google Translate init error:', e);
                    googleTranslateLoaded = false;
                }
            };
        } catch (e) {
            console.error('Google Translate setup error:', e);
        }
    }

    /**
     * Change language using Google Translate
     */
    function changeLanguage(langCode) {
        const lang = languageCodes[langCode] || 'en';
        console.log('🌐 Changing language to:', lang);

        try {
            // Method 1: Try using Google Translate select element
            if (googleTranslateLoaded && window.google && window.google.translate) {
                const select = document.querySelector('#google_translate_element select');
                if (select) {
                    const options = Array.from(select.options);
                    for (let i = 0; i < options.length; i++) {
                        const optionValue = options[i].value;
                        if (optionValue.includes('|' + lang) || 
                            (lang === 'en' && optionValue.includes('|en'))) {
                            select.selectedIndex = i;
                            select.dispatchEvent(new Event('change', { bubbles: true }));
                            console.log('✅ Language changed via Google Translate');
                            return;
                        }
                    }
                }
            }

            // Method 2: If Google Translate not ready, reload page with language parameter
            console.log('⚠️ Google Translate not ready, reloading page...');
            const currentUrl = window.location.href;
            const url = new URL(currentUrl);
            if (lang !== 'en') {
                url.searchParams.set('hl', lang);
            } else {
                url.searchParams.delete('hl');
            }
            window.location.href = url.toString();

        } catch (e) {
            console.error('Language change error:', e);
            // Fallback: reload page
            setTimeout(() => { location.reload(); }, 300);
        }
    }

    /**
     * Initialize language translator
     */
    function initLanguageTranslator() {
        try {
            // Initialize Google Translate on page load (non-blocking)
            setTimeout(() => {
                initGoogleTranslate();
            }, 500);

            // Listen for language changes from dropdown
            setTimeout(() => {
                const languageSelect = document.getElementById('languageSelect');
                if (languageSelect && !languageSelect.dataset.listenerAdded) {
                    languageSelect.dataset.listenerAdded = 'true';
                    languageSelect.addEventListener('change', function() {
                        const langCode = this.value;
                        changeLanguage(langCode);
                    });
                }
            }, 500);

        } catch (e) {
            console.error('Language translator init error:', e);
        }
    }

    // Initialize when DOM is ready (non-blocking)
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            setTimeout(initLanguageTranslator, 200);
        });
    } else {
        setTimeout(initLanguageTranslator, 200);
    }

    // Export for manual use
    window.languageTranslator = {
        changeLanguage: changeLanguage,
        init: initGoogleTranslate
    };
})();
