/**
 * AUTO TESTER - Multilingual Language System
 * Supports Arabic and English languages with RTL/LTR switching
 */

class LanguageSystem {
    constructor() {
        this.currentLanguage = localStorage.getItem('language') || 'ar';
        this.translations = {};
        this.isInitialized = false;
        
        // Language configurations
        this.languages = {
            ar: {
                name: 'Arabic',
                code: 'ar',
                direction: 'rtl',
                fontFamily: 'Cairo, sans-serif'
            },
            en: {
                name: 'English',
                code: 'en',
                direction: 'ltr',
                fontFamily: 'Arial, sans-serif'
            }
        };
        
        this.init();
    }
    
    async init() {
        try {
            // Load translations
            await this.loadTranslations();
            
            // Apply current language
            this.applyLanguage(this.currentLanguage);
            
            // Setup language switcher
            this.setupLanguageSwitcher();
            
            // Setup dynamic content translation
            this.setupDynamicTranslation();
            
            this.isInitialized = true;
            
            // Dispatch ready event
            document.dispatchEvent(new CustomEvent('languageSystemReady'));
            
        } catch (error) {
            console.error('Language system initialization error:', error);
        }
    }
    
    async loadTranslations() {
        try {
            // Load Arabic translations
            const arResponse = await fetch('/assets/lang/ar.json');
            this.translations.ar = await arResponse.json();
            
            // Load English translations
            const enResponse = await fetch('/assets/lang/en.json');
            this.translations.en = await enResponse.json();
            
        } catch (error) {
            console.error('Error loading translations:', error);
            
            // Fallback translations
            this.translations = {
                ar: this.getFallbackArabicTranslations(),
                en: this.getFallbackEnglishTranslations()
            };
        }
    }
    
    applyLanguage(languageCode) {
        const lang = this.languages[languageCode];
        if (!lang) return;
        
        // Update HTML lang attribute
        document.documentElement.lang = languageCode;
        
        // Update direction
        document.documentElement.dir = lang.direction;
        document.body.dir = lang.direction;
        
        // Update font family
        document.body.style.fontFamily = lang.fontFamily;
        
        // Update language class
        document.body.classList.remove('lang-ar', 'lang-en');
        document.body.classList.add(`lang-${languageCode}`);
        
        // Translate static elements
        this.translateStaticElements();
        
        // Update language switcher
        this.updateLanguageSwitcher(languageCode);
        
        // Save preference
        localStorage.setItem('language', languageCode);
        
        this.currentLanguage = languageCode;
        
        // Dispatch change event
        document.dispatchEvent(new CustomEvent('languageChanged', {
            detail: { language: languageCode, config: lang }
        }));
    }
    
    translateStaticElements() {
        const elements = document.querySelectorAll('[data-translate]');
        
        elements.forEach(element => {
            const key = element.getAttribute('data-translate');
            const translation = this.getTranslation(key);
            
            if (translation) {
                // Handle different element types
                if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {
                    element.placeholder = translation;
                } else if (element.tagName === 'OPTION') {
                    element.textContent = translation;
                } else {
                    element.textContent = translation;
                }
            }
        });
    }
    
    getTranslation(key, params = {}) {
        const translation = this.translations[this.currentLanguage]?.[key] || key;
        
        // Replace parameters in translation
        if (params && typeof translation === 'string') {
            return translation.replace(/\{\{(\w+)\}\}/g, (match, param) => {
                return params[param] || match;
            });
        }
        
        return translation;
    }
    
    setupLanguageSwitcher() {
        // Create language switcher if not exists
        let switcher = document.getElementById('languageSwitcher');
        
        if (!switcher) {
            switcher = document.createElement('div');
            switcher.id = 'languageSwitcher';
            switcher.className = 'language-switcher';
            
            // Add to header or navigation
            const header = document.querySelector('.header') || document.querySelector('.nav-container') || document.body;
            if (header) {
                header.appendChild(switcher);
            }
        }
        
        this.updateLanguageSwitcher(this.currentLanguage);
    }
    
    updateLanguageSwitcher(currentLang) {
        const switcher = document.getElementById('languageSwitcher');
        if (!switcher) return;
        
        switcher.innerHTML = '';
        
        Object.entries(this.languages).forEach(([code, config]) => {
            const button = document.createElement('button');
            button.className = `lang-btn ${code === currentLang ? 'active' : ''}`;
            button.setAttribute('data-lang', code);
            button.textContent = config.name;
            
            button.addEventListener('click', () => {
                this.switchLanguage(code);
            });
            
            switcher.appendChild(button);
        });
    }
    
    switchLanguage(languageCode) {
        if (!this.languages[languageCode] || languageCode === this.currentLanguage) {
            return;
        }
        
        // Show loading
        this.showLanguageLoading();
        
        // Apply new language
        this.applyLanguage(languageCode);
        
        // Hide loading
        setTimeout(() => {
            this.hideLanguageLoading();
        }, 300);
    }
    
    setupDynamicTranslation() {
        // Observe DOM changes for new elements
        if (window.MutationObserver) {
            const observer = new MutationObserver((mutations) => {
                mutations.forEach((mutation) => {
                    if (mutation.type === 'childList') {
                        mutation.addedNodes.forEach((node) => {
                            if (node.nodeType === Node.ELEMENT_NODE) {
                                this.translateElement(node);
                            }
                        });
                    }
                });
            });
            
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
        }
    }
    
    translateElement(element) {
        // Check if element has translate attribute
        if (element.hasAttribute && element.hasAttribute('data-translate')) {
            const key = element.getAttribute('data-translate');
            const translation = this.getTranslation(key);
            
            if (translation) {
                if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {
                    element.placeholder = translation;
                } else {
                    element.textContent = translation;
                }
            }
        }
        
        // Translate child elements
        const childElements = element.querySelectorAll ? element.querySelectorAll('[data-translate]') : [];
        childElements.forEach(child => this.translateElement(child));
    }
    
    showLanguageLoading() {
        const loader = document.createElement('div');
        loader.id = 'languageLoader';
        loader.className = 'language-loader';
        loader.innerHTML = '<div class="spinner"></div>';
        document.body.appendChild(loader);
    }
    
    hideLanguageLoading() {
        const loader = document.getElementById('languageLoader');
        if (loader) {
            loader.remove();
        }
    }
    
    // Get current language
    getCurrentLanguage() {
        return this.currentLanguage;
    }
    
    // Get current language config
    getCurrentLanguageConfig() {
        return this.languages[this.currentLanguage];
    }
    
    // Check if RTL
    isRTL() {
        return this.currentLanguage === 'ar';
    }
    
    // Format number for current language
    formatNumber(number) {
        try {
            return new Intl.NumberFormat(this.currentLanguage === 'ar' ? 'ar-EG' : 'en-US').format(number);
        } catch (error) {
            return number.toString();
        }
    }
    
    // Format currency for current language
    formatCurrency(amount, currency = 'EGP') {
        try {
            return new Intl.NumberFormat(
                this.currentLanguage === 'ar' ? 'ar-EG' : 'en-US',
                {
                    style: 'currency',
                    currency: currency,
                    minimumFractionDigits: 0,
                    maximumFractionDigits: 0
                }
            ).format(amount);
        } catch (error) {
            return `${amount} ${currency}`;
        }
    }
    
    // Format date for current language
    formatDate(date, options = {}) {
        try {
            const defaultOptions = {
                year: 'numeric',
                month: 'long',
                day: 'numeric'
            };
            
            return new Intl.DateTimeFormat(
                this.currentLanguage === 'ar' ? 'ar-EG' : 'en-US',
                { ...defaultOptions, ...options }
            ).format(new Date(date));
        } catch (error) {
            return date.toString();
        }
    }
    
    // Fallback translations
    getFallbackArabicTranslations() {
        return {
            // Navigation
            'nav.dashboard': 'Dashboard',
            'nav.inspections': 'Inspections',
            'nav.reports': 'Reports',
            'nav.settings': 'Settings',
            'nav.logout': 'Logout',
            
            // Common
            'common.loading': 'Loading...',
            'common.error': 'Error',
            'common.success': 'Success',
            'common.save': 'Save',
            'common.cancel': 'Cancel',
            'common.delete': 'Delete',
            'common.edit': 'Edit',
            'common.view': 'View',
            'common.search': 'Search',
            'common.filter': 'Filter',
            'common.export': 'Export',
            'common.print': 'Print',
            
            // Authentication
            'auth.login': 'Login',
            'auth.username': 'Username',
            'auth.password': 'Password',
            'auth.remember': 'Remember me',
            'auth.forgot': 'Forgot password?',
            
            // Inspection
            'inspection.title': 'Vehicle Inspection',
            'inspection.type': 'Inspection Type',
            'inspection.status': 'Status',
            'inspection.date': 'Date',
            'inspection.inspector': 'Inspector',
            'inspection.customer': 'Customer',
            'inspection.vehicle': 'Vehicle',
            'inspection.results': 'Results',
            
            // Status
            'status.pending': 'Pending',
            'status.in_progress': 'In Progress',
            'status.completed': 'Completed',
            'status.cancelled': 'Cancelled',
            
            // Vehicle Rating
            'rating.title': 'Vehicle Rating',
            'rating.overall': 'Overall Condition',
            'rating.excellent': 'Excellent',
            'rating.very_good': 'Very Good',
            'rating.good': 'Good',
            'rating.fair': 'Fair',
            'rating.poor': 'Poor',
            
            // Pricing
            'pricing.title': 'Vehicle Pricing',
            'pricing.base_price': 'Base Price',
            'pricing.final_price': 'Estimated Price',
            'pricing.range': 'Price Range',
            'pricing.mileage': 'Mileage',
            'pricing.depreciation': 'Depreciation',
            
            // Messages
            'msg.login_required': 'Login required',
            'msg.inspection_not_found': 'Inspection not found',
            'msg.save_success': 'Saved successfully',
            'msg.delete_confirm': 'Are you sure you want to delete?',
            'msg.operation_success': 'Operation completed successfully'
        };
    }
    
    getFallbackEnglishTranslations() {
        return {
            // Navigation
            'nav.dashboard': 'Dashboard',
            'nav.inspections': 'Inspections',
            'nav.reports': 'Reports',
            'nav.settings': 'Settings',
            'nav.logout': 'Logout',
            
            // Common
            'common.loading': 'Loading...',
            'common.error': 'Error',
            'common.success': 'Success',
            'common.save': 'Save',
            'common.cancel': 'Cancel',
            'common.delete': 'Delete',
            'common.edit': 'Edit',
            'common.view': 'View',
            'common.search': 'Search',
            'common.filter': 'Filter',
            'common.export': 'Export',
            'common.print': 'Print',
            
            // Authentication
            'auth.login': 'Login',
            'auth.username': 'Username',
            'auth.password': 'Password',
            'auth.remember': 'Remember me',
            'auth.forgot': 'Forgot password?',
            
            // Inspection
            'inspection.title': 'Vehicle Inspection',
            'inspection.type': 'Inspection Type',
            'inspection.status': 'Status',
            'inspection.date': 'Date',
            'inspection.inspector': 'Inspector',
            'inspection.customer': 'Customer',
            'inspection.vehicle': 'Vehicle',
            'inspection.results': 'Results',
            
            // Status
            'status.pending': 'Pending',
            'status.in_progress': 'In Progress',
            'status.completed': 'Completed',
            'status.cancelled': 'Cancelled',
            
            // Vehicle Rating
            'rating.title': 'Vehicle Rating',
            'rating.overall': 'Overall Condition',
            'rating.excellent': 'Excellent',
            'rating.very_good': 'Very Good',
            'rating.good': 'Good',
            'rating.fair': 'Fair',
            'rating.poor': 'Poor',
            
            // Pricing
            'pricing.title': 'Vehicle Pricing',
            'pricing.base_price': 'Base Price',
            'pricing.final_price': 'Estimated Price',
            'pricing.range': 'Price Range',
            'pricing.mileage': 'Mileage',
            'pricing.depreciation': 'Depreciation',
            
            // Messages
            'msg.login_required': 'Login required',
            'msg.inspection_not_found': 'Inspection not found',
            'msg.save_success': 'Saved successfully',
            'msg.delete_confirm': 'Are you sure you want to delete?',
            'msg.operation_success': 'Operation completed successfully'
        };
    }
}

// Initialize language system
const languageSystem = new LanguageSystem();

// Global functions for backward compatibility
window.t = (key, params) => languageSystem.getTranslation(key, params);
window.currentLang = () => languageSystem.getCurrentLanguage();
window.isRTL = () => languageSystem.isRTL();
window.formatNumber = (num) => languageSystem.formatNumber(num);
window.formatCurrency = (amount, currency) => languageSystem.formatCurrency(amount, currency);
window.formatDate = (date, options) => languageSystem.formatDate(date, options);

// Export for ES6 modules
if (typeof module !== 'undefined' && module.exports) {
    module.exports = LanguageSystem;
}
