import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import LanguageDetector from 'i18next-browser-languagedetector'
import en from './en.json'
import ko from './ko.json'

export const SUPPORTED_LANGS = ['en', 'ko'] as const
export type Lang = (typeof SUPPORTED_LANGS)[number]
const STORAGE_KEY = 'mall_lang'

// 선택 언어에 맞춰 <html lang>과 한글 폰트 토글(.lang-ko)을 동기화
export function applyLangSideEffects(lng: string) {
  const base = (lng || 'en').split('-')[0]
  const lang = (SUPPORTED_LANGS as readonly string[]).includes(base) ? base : 'en'
  const html = document.documentElement
  html.setAttribute('lang', lang)
  // 한국어 선택 시 본문 폰트를 맑은 고딕 우선으로(.lang-ko CSS 적용)
  html.classList.toggle('lang-ko', lang === 'ko')
}

i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    resources: {
      en: { translation: en },
      ko: { translation: ko },
    },
    fallbackLng: 'en', // 기본 언어 영어(US 시장)
    supportedLngs: SUPPORTED_LANGS as unknown as string[],
    nonExplicitSupportedLngs: true,
    load: 'languageOnly',
    interpolation: { escapeValue: false },
    detection: {
      // localStorage에 선택 영속 → 없으면 브라우저 언어 감지
      order: ['localStorage', 'navigator', 'htmlTag'],
      lookupLocalStorage: STORAGE_KEY,
      caches: ['localStorage'],
    },
  })

applyLangSideEffects(i18n.language)
i18n.on('languageChanged', applyLangSideEffects)

export default i18n
