import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import appBridge from '@/utils/appBridge';

import ko from './ko.json';
import en from './en.json';

// 초기 언어 설정
let initialLanguage = 'ko';

// 네이티브 환경이 아닐 때는 localStorage에서 확인
if (!appBridge.isNativeEnvironment()) {
  const storedLanguage = localStorage.getItem('i18nextLng');
  if (storedLanguage && (storedLanguage === 'ko' || storedLanguage === 'en')) {
    initialLanguage = storedLanguage;
  }
} else {
  // 네이티브 환경에서는 네이티브 언어를 가져와 localStorage에 설정
  try {
    appBridge.getLanguage().then((language) => {
      if (language && typeof language === 'string' && (language === 'ko' || language === 'en')) {
        localStorage.setItem('i18nextLng', language);
        // i18n이 이미 초기화된 경우 언어 변경
        if (i18n.isInitialized && i18n.language !== language) {
          i18n.changeLanguage(language);
        }
      }
    }).catch((error) => {
      console.warn('Failed to get native language during init:', error);
    });
  } catch (error) {
    console.warn('Failed to get native language:', error);
  }
}

i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    resources: {
      en: {translation: en},
      ko: {translation: ko},
    },
    lng: initialLanguage,
    fallbackLng: 'ko',
    debug: true,
    interpolation: {
      escapeValue: false,
    },
    detection: {
      order: ['localStorage', 'navigator'],
      caches: ['localStorage'],
    }
  });

export default i18n;