import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

// Resource files live at ./locales/{lng}/{namespace}.json. Each UI area owns its
// own namespace file so parallel string-extraction work never collides on a
// shared resource file. Adding a new {lng}/{ns}.json is auto-registered here via
// Vite's glob import — no edit to this file needed.
const modules = import.meta.glob('./locales/*/*.json', { eager: true }) as Record<
  string,
  { default: Record<string, unknown> }
>;

const resources: Record<string, Record<string, Record<string, unknown>>> = {};
const namespaces = new Set<string>();
for (const [path, mod] of Object.entries(modules)) {
  // path looks like ./locales/en/settings.json
  const m = path.match(/\.\/locales\/([^/]+)\/([^/]+)\.json$/);
  if (!m) continue;
  const [, lng, ns] = m;
  namespaces.add(ns);
  resources[lng] ??= {};
  resources[lng][ns] = mod.default;
}

export const SUPPORTED_LANGUAGES = ['en', 'ja'] as const;
export type SupportedLanguage = (typeof SUPPORTED_LANGUAGES)[number];
export const LANGUAGE_STORAGE_KEY = 'maestro.lang';

void i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    resources,
    ns: Array.from(namespaces),
    defaultNS: 'common',
    fallbackLng: 'en',
    supportedLngs: SUPPORTED_LANGUAGES as unknown as string[],
    nonExplicitSupportedLngs: true, // ja-JP -> ja
    interpolation: { escapeValue: false }, // React already escapes
    detection: {
      // Prefer an explicit user choice (localStorage), then the browser.
      order: ['localStorage', 'navigator'],
      lookupLocalStorage: LANGUAGE_STORAGE_KEY,
      caches: ['localStorage'],
    },
    returnEmptyString: false, // empty stub values fall back to the key/fallbackLng
  });

export default i18n;
