import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

import koCommon from './locales/ko/common.json';
import koEvents from './locales/ko/events.json';
import koShips from './locales/ko/ships.json';
import enCommon from './locales/en/common.json';
import enEvents from './locales/en/events.json';
import enShips from './locales/en/ships.json';

const STORAGE_KEY = 'kcg:lang';

function readStoredLang(): string {
  try {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored === 'ko' || stored === 'en') return stored;
  } catch {
    // localStorage unavailable
  }
  return 'ko';
}

i18n.use(initReactI18next).init({
  resources: {
    ko: { common: koCommon, events: koEvents, ships: koShips },
    en: { common: enCommon, events: enEvents, ships: enShips },
  },
  lng: readStoredLang(),
  fallbackLng: 'ko',
  defaultNS: 'common',
  ns: ['common', 'events', 'ships'],
  interpolation: { escapeValue: false },
});

// Persist language changes
i18n.on('languageChanged', (lng) => {
  try {
    localStorage.setItem(STORAGE_KEY, lng);
  } catch {
    // localStorage unavailable
  }
});

export default i18n;
