'use client'

import { createContext, useContext } from 'react'
import type { ReactNode } from 'react'
import { defaultI18n, t, type Dictionary } from '.'
import type { SupportedLanguage } from '@/lib/user-language'

type I18nContextValue = {
  language: SupportedLanguage
  dictionary: Dictionary
  t: (key: string, replacements?: Record<string, string | number>) => string
}

const I18nContext = createContext<I18nContextValue>(defaultI18n())

export function I18nProvider({
  language,
  dictionary,
  children,
}: {
  language: SupportedLanguage
  dictionary: Dictionary
  children: ReactNode
}) {
  return (
    <I18nContext.Provider
      value={{
        language,
        dictionary,
        t: (key, replacements) => t(dictionary, key, replacements),
      }}
    >
      {children}
    </I18nContext.Provider>
  )
}

export function useI18n(): I18nContextValue {
  return useContext(I18nContext)
}
