class AvisionI18n {
    constructor() {
        this.currentLanguage = 'en';
        this.translations = {};
        this.supportedLanguages = ['en', 'fr', 'es'];
    }

    async init() {
        this.detectLanguage();
        await this.loadTranslations();
        this.updateAllTexts();
        this.setupFlagListeners();
    }

    detectLanguage() {
        const urlParams = new URLSearchParams(window.location.search);
        const urlLang = urlParams.get('lang');
        
        if (urlLang && this.supportedLanguages.includes(urlLang)) {
            this.currentLanguage = urlLang;
            localStorage.setItem('avision_lang', urlLang);
        } else {
            const storedLang = localStorage.getItem('avision_lang');
            if (storedLang && this.supportedLanguages.includes(storedLang)) {
                this.currentLanguage = storedLang;
            }
        }
    }

    async loadTranslations() {
        try {
            const response = await fetch(`/wordpress/wp-content/plugins/avision-dashboard/languages/${this.currentLanguage}.json`);
            this.translations = await response.json();
        } catch (error) {
            console.error('Failed to load translations:', error);
            if (this.currentLanguage !== 'en') {
                this.currentLanguage = 'en';
                await this.loadTranslations();
            }
        }
    }

    get(key, defaultValue = '') {
        return this.translations[key] || defaultValue || key;
    }

    updateAllTexts() {
        document.querySelectorAll('[data-i18n]').forEach(element => {
            const key = element.getAttribute('data-i18n');
            const text = this.get(key);
            if (text) {
                element.textContent = text;
            }
        });

        document.querySelectorAll('[data-i18n-placeholder]').forEach(element => {
            const key = element.getAttribute('data-i18n-placeholder');
            const text = this.get(key);
            if (text) {
                element.placeholder = text;
            }
        });

        document.querySelectorAll('[data-i18n-value]').forEach(element => {
            const key = element.getAttribute('data-i18n-value');
            const text = this.get(key);
            if (text) {
                element.value = text;
            }
        });

        document.querySelectorAll('.flag-btn').forEach(btn => {
            btn.classList.remove('active');
            if (btn.dataset.lang === this.currentLanguage) {
                btn.classList.add('active');
            }
        });

        const yearElements = document.querySelectorAll('[data-dynamic-year]');
        yearElements.forEach(el => {
            el.textContent = new Date().getFullYear();
        });
    }

    setupFlagListeners() {
        document.querySelectorAll('.flag-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                const lang = btn.dataset.lang;
                if (lang && this.supportedLanguages.includes(lang)) {
                    this.switchLanguage(lang);
                }
            });
        });
    }

    async switchLanguage(lang) {
        if (lang === this.currentLanguage) return;
        
        this.currentLanguage = lang;
        localStorage.setItem('avision_lang', lang);
        await this.loadTranslations();
        this.updateAllTexts();

        document.dispatchEvent(new CustomEvent('languageChanged', { 
            detail: { language: lang, translations: this.translations }
        }));
    }

    getCurrentLanguage() {
        return this.currentLanguage;
    }

    getCurrency() {
        return this.currentLanguage === 'en' ? 'USD' : 'EUR';
    }

    getCurrencySymbol() {
        return this.currentLanguage === 'en' ? '$' : '€';
    }

    getPrice(type = 'dashboard') {
        const symbol = this.getCurrencySymbol();
        if (type === 'dashboard') {
            return `${symbol}99`;
        } else if (type === 'automation') {
            return `${symbol}29/month`;
        }
        return `${symbol}0`;
    }
}

window.avisionI18n = new AvisionI18n();
