document.addEventListener('DOMContentLoaded', () => {
    const languageSelector = document.getElementById('language-selector');
    const currentLang = localStorage.getItem('appLang') || 'es'; // Default to Spanish

    const translatableElements = document.querySelectorAll('[data-translate="true"]');

    // Function to translate text
    async function translateText(text, sourceLang, targetLang) {
        try {
            const response = await fetch('/translate_proxy.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'translate',
                    text: text,
                    source: sourceLang,
                    target: targetLang
                }),
            });
            const data = await response.json();
            if (response.ok) {
                return data.translatedText; // LibreTranslate returns { translatedText: "..." }
            } else {
                console.error('Error translating:', data.error);
                return text; // Return original text on error
            }
        } catch (error) {
            console.error('Network error during translation:', error);
            return text; // Return original text on network error
        }
    }

    async function applyTranslation(targetLang) {
        for (const element of translatableElements) {
            const originalText = element.dataset.originalText || element.textContent;
            if (!element.dataset.originalText) {
                element.dataset.originalText = originalText;
            }

            const icon = element.querySelector('i.bi');
            const textToTranslate = originalText.trim();

            let newText;
            if (targetLang === 'es') {
                newText = textToTranslate;
            } else {
                newText = await translateText(textToTranslate, 'es', targetLang);
            }

            if (icon) {
                element.textContent = ' ' + newText;
                element.insertAdjacentHTML('afterbegin', icon.outerHTML);
            } else {
                element.textContent = newText;
            }
        }
        localStorage.setItem('appLang', targetLang);
        if (languageSelector) {
            languageSelector.value = targetLang;
        }
    }

    // Function to fetch and populate languages
    async function fetchAndPopulateLanguages() {
        try {
            const response = await fetch('/translate_proxy.php?action=languages'); // Assuming translate_proxy.php can handle a 'languages' action
            const languages = await response.json();
            if (response.ok && Array.isArray(languages)) {
                languageSelector.innerHTML = ''; // Clear existing options
                languages.forEach(lang => {
                    const option = document.createElement('option');
                    option.value = lang.code;
                    option.textContent = `${lang.flag_emoji} ${lang.name}`;
                    languageSelector.appendChild(option);
                });
                // Set the selector to the current language
                languageSelector.value = currentLang;
            } else {
                console.error('Error fetching languages:', languages.error || 'Unknown error');
                // Fallback to default options if fetching fails
                languageSelector.innerHTML = `
                    <option value="es">🇪🇸 Español</option>
                    <option value="en">🇬🇧 English</option>
                    <option value="pt">🇧🇷 Português</option>
                `;
                languageSelector.value = currentLang;
            }
        } catch (error) {
            console.error('Network error fetching languages:', error);
            // Fallback to default options if network error
            languageSelector.innerHTML = `
                <option value="es">🇪🇸 Español</option>
                <option value="en">🇬🇧 English</option>
                <option value="pt">🇧🇷 Português</option>
            `;
            languageSelector.value = currentLang;
        }
    }

    // Initial application of language based on stored preference
    fetchAndPopulateLanguages().then(() => {
        applyTranslation(currentLang);
    });

    // Event listener for the language selector
    if (languageSelector) {
        languageSelector.addEventListener('change', (event) => {
            const newLang = event.target.value;
            applyTranslation(newLang);
        });
    }
});