/**
 * 国际化工具库
 * Simple i18n implementation without external dependencies
 */

export type Locale = 'zh' | 'en';

export const locales: Locale[] = ['zh', 'en'];

export const localeNames: Record<Locale, string> = {
  zh: '中文',
  en: 'English',
};

// 翻译字典类型
export type Translations = {
  [key: string]: string | Translations;
};

// 获取嵌套翻译
export function getTranslation(translations: Translations, key: string): string {
  const keys = key.split('.');
  let result: Translations | string = translations;
  
  for (const k of keys) {
    if (result && typeof result === 'object' && k in result) {
      result = result[k] as Translations | string;
    } else {
      return key; // 返回 key 作为 fallback
    }
  }
  
  return typeof result === 'string' ? result : key;
}

// 默认语言
export const defaultLocale: Locale = 'en';

// 获取当前语言
export function getCurrentLocale(): Locale {
  if (typeof window === 'undefined') return defaultLocale;
  
  const stored = localStorage.getItem('locale');
  if (stored && locales.includes(stored as Locale)) {
    return stored as Locale;
  }
  
  return defaultLocale;
}

// 设置当前语言
export function setCurrentLocale(locale: Locale): void {
  if (typeof window === 'undefined') return;
  localStorage.setItem('locale', locale);
  window.dispatchEvent(new CustomEvent('ffoa-locale-change', { detail: locale }));
}
