import i18next from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import ChainedBackend from 'i18next-chained-backend';
import HttpBackend from 'i18next-http-backend';
import LocalStorageBackend from 'i18next-localstorage-backend';
import resourcesToBackend from 'i18next-resources-to-backend';
import { initReactI18next } from 'react-i18next';

// Automatically incremented by `suno-app-ui-i18n-version.yml` workflow
import TRANSLATIONS_VERSION from '../../public/locales/version.json';

const isBrowser = typeof window !== 'undefined';
const isDev = process.env.NODE_ENV === 'development';

i18next
  .use(ChainedBackend)
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    debug: false,
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false,
    },
    supportedLngs: ['en'],
    backend: isDev
      ? // DEV
        isBrowser
        ? // Browser: Load over HTTP
          {
            backends: [HttpBackend],
            backendOptions: [{ loadPath: '/locales/{{lng}}/{{ns}}.json' }],
          }
        : // App: Load over HTTP, fallback to lazy import
          {
            backends: [
              HttpBackend,
              resourcesToBackend(
                (language: string, namespace: string) =>
                  import(`../../public/locales/${language}/${namespace}.json`)
              ),
            ],
            backendOptions: [
              // The calls are coming from inside the house, but a hostname is required.
              { loadPath: 'http://localhost:3000/locales/{{lng}}/{{ns}}.json' },
            ],
          }
      : // PRODUCTION
        isBrowser
        ? // Browser: Use localStorage cache, fall back to HTTP request
          {
            backends: [LocalStorageBackend, HttpBackend],
            backendOptions: [
              {
                defaultVersion: TRANSLATIONS_VERSION.translation,
                versions: TRANSLATIONS_VERSION,
              },
              {
                loadPath(lng: string, ns: string) {
                  const version =
                    ns in TRANSLATIONS_VERSION
                      ? TRANSLATIONS_VERSION[
                          ns as keyof typeof TRANSLATIONS_VERSION
                        ]
                      : TRANSLATIONS_VERSION.translation;
                  return version
                    ? `/locales/${lng}/${ns}.json?v=${version}`
                    : `/locales/${lng}/${ns}.json`;
                },
              },
            ],
          }
        : // App: Lazy import
          {
            backends: [
              resourcesToBackend((language: string, namespace: string) => {
                return import(
                  `../../public/locales/${language}/${namespace}.json`
                );
              }),
            ],
          },
    load: 'languageOnly',
  });

export default i18next;
