const i18n = { locale: localStorage.getItem('locale') || 'en', translations: {}, async init() { await this.loadTranslations(this.locale); this.translatePage(); }, async loadTranslations(locale) { try { const response = await fetch(`/api/i18n/${locale}`); const data = await response.json(); if (data.success) { this.translations = data.translations; this.locale = locale; } } catch (error) { console.error('Failed to load translations:', error); } }, t(key) { const keys = key.split('.'); let value = this.translations; for (const k of keys) { if (value && typeof value === 'object') { value = value[k]; } else { return key; } } return value || key; }, translatePage() { document.querySelectorAll('[data-i18n]').forEach(element => { const key = element.getAttribute('data-i18n'); const translation = this.t(key); if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') { element.placeholder = translation; } else { element.textContent = translation; } }); const langNames = { 'en': 'EN', 'zh_CN': '中文', 'es': 'ES' }; const currentLangElement = document.getElementById('currentLang'); if (currentLangElement) { currentLangElement.textContent = langNames[this.locale] || 'EN'; } }, async switchLanguage(locale) { await this.loadTranslations(locale); this.translatePage(); localStorage.setItem('locale', locale); } }; document.getElementById('languageToggle')?.addEventListener('click', async () => { const locales = ['en', 'zh_CN', 'es']; const next = locales[(locales.indexOf(i18n.locale) + 1) % locales.length]; await i18n.switchLanguage(next); }); document.addEventListener('DOMContentLoaded', () => { i18n.init(); });