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

import deCommon from './locales/de/common.json';
import enCommon from './locales/en/common.json';
import deDashboard from './locales/de/dashboard.json';
import enDashboard from './locales/en/dashboard.json';
import deOnboarding from './locales/de/onboarding.json';
import enOnboarding from './locales/en/onboarding.json';
import deManagement from './locales/de/management.json';
import enManagement from './locales/en/management.json';
import deSettings from './locales/de/settings.json';
import enSettings from './locales/en/settings.json';
import deAuth from './locales/de/auth.json';
import enAuth from './locales/en/auth.json';
import deMobile from './locales/de/mobile.json';
import enMobile from './locales/en/mobile.json';

const DEFAULT_NAMESPACE = 'common';

const resources = {
  de: {
    common: deCommon,
    dashboard: deDashboard,
    onboarding: deOnboarding,
    management: deManagement,
    settings: deSettings,
    auth: deAuth,
    mobile: deMobile,
  },
  en: {
    common: enCommon,
    dashboard: enDashboard,
    onboarding: enOnboarding,
    management: enManagement,
    settings: enSettings,
    auth: enAuth,
    mobile: enMobile,
  },
} as const;

const FALLBACK_LOCALE = 'de';
const NAMESPACES = ['common', 'dashboard', 'onboarding', 'management', 'settings', 'auth', 'mobile'] as const;

if (!i18n.isInitialized) {
  i18n
    .use(LanguageDetector)
    .use(initReactI18next)
    .init({
      resources,
      fallbackLng: FALLBACK_LOCALE,
      lng: document.documentElement.lang || undefined,
      supportedLngs: ['de', 'en'],
      ns: NAMESPACES,
      defaultNS: DEFAULT_NAMESPACE,
      fallbackNS: DEFAULT_NAMESPACE,
      interpolation: {
        escapeValue: false,
      },
      detection: {
        order: ['htmlTag', 'localStorage', 'cookie', 'navigator'],
        caches: ['localStorage'],
        htmlTag: document.documentElement,
      },
      returnEmptyString: false,
    })
    .catch((error) => {
      if (import.meta.env.DEV) {
         
        console.error('Failed to initialize i18n', error);
      }
    });
}

export default i18n;
