import { createI18n } from 'vue-i18n';
import en from './locales/en.json';
import me from './locales/me.json';
import ru from './locales/ru.json';
import ua from './locales/ua.json';

const savedLocale = localStorage.getItem('locale') || 'en';

const i18n = createI18n({
  legacy: false,
  locale: savedLocale,
  fallbackLocale: 'en',
  enableDevtools: false,
  messages: {
    en,
    me,
    ru,
    ua
  }
});

// Robust deep merge for locale objects
const deepMerge = (target: any, source: any) => {
  if (!source) return target;
  
  Object.keys(source).forEach(key => {
    const sVal = source[key];
    const tVal = target[key];
    
    if (sVal !== null && typeof sVal === 'object' && !Array.isArray(sVal)) {
      if (!tVal || typeof tVal !== 'object') {
        target[key] = {};
      }
      deepMerge(target[key], sVal);
    } else {
      target[key] = sVal;
    }
  });
  return target;
};

export const loadAdminTranslations = async (lang?: string) => {
  const targetLang = lang || (i18n.global as any).locale.value;
  console.log(`[i18n] Loading admin translations for: ${targetLang}...`);
  try {
    const module = await import(`./locales/${targetLang}.admin.json`);
    let newMessages = module.default || module;
    
    // Ensure the structure is correct: { admin: { ... } }
    if (!newMessages.admin && (newMessages.tabs || newMessages.actions || newMessages.managementCenter)) {
       newMessages = { admin: newMessages };
    }

    // getLocaleMessage returns a copy in Composer mode
    const currentMessages = i18n.global.getLocaleMessage(targetLang);
    
    // Perform deep merge
    const merged = deepMerge({ ...currentMessages }, newMessages);
    
    // Explicitly set the updated message object back to the locale
    i18n.global.setLocaleMessage(targetLang, merged);
    
    console.log(`[i18n] Admin translations successfully loaded and merged for: ${targetLang}`);
  } catch (error) {
    console.error(`[i18n] Failed to load admin translations for ${targetLang}:`, error);
  }
};

export const setLanguage = async (lang: string) => {
  (i18n.global as any).locale.value = lang;
  localStorage.setItem('locale', lang);
  
  // If we are in an admin-related path, we might want to load admin translations for the new language
  if (window.location.pathname.startsWith('/admin')) {
    await loadAdminTranslations(lang);
  }
};
export const currentLanguage = () => (i18n.global as any).locale.value as string;
export default i18n;
