import React, { type ReactNode } from 'react'
import { I18nextProvider } from 'react-i18next'
import { createInstance, type i18n as I18n, type Resource } from 'i18next'

export const newTranslationInstance = (resources: Resource): I18n => {
  const isDebugMode =
    typeof window !== 'undefined' &&
    typeof localStorage !== 'undefined' &&
    localStorage.getItem('debug-translations') === 'true'
  return createInstance({
    debug: isDebugMode,
    appendNamespaceToCIMode: isDebugMode,
    fallbackLng: isDebugMode ? 'cimode' : 'en',
    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
    },
    lng: isDebugMode ? 'cimode' : 'en',
    resources,
  })
}

export const TranslationProvider = ({
  children,
  i18nInstance,
}: {
  children: ReactNode
  i18nInstance: I18n
}) => (
  <I18nextProvider i18n={i18nInstance} defaultNS='en'>
    {children}
  </I18nextProvider>
)

export { Trans as Translate, useTranslation } from 'react-i18next'

/** @deprecated, use the tr function instead */
export const translate = (
  namespaceAndKey: `${string}:${string}`,
  i18nInstance: I18n,
) => i18nInstance.t(namespaceAndKey)

export const tr = (
  namespaceAndKey: `${string}:${string}`,
  i18nInstance: I18n,
  values?: Record<string, unknown>,
) => i18nInstance.t(namespaceAndKey, values)
