import { useCallback } from 'react'

import { useLocalStore } from 'hooks'

import type { Languages } from 'config/languages'

import { isSupportedLang } from '../helpers/isSupportedLang'

const LANG_KEY = 'lang'
const DEFAULT_LANG = 'en'

export const useLang = () => {
  const [lang, setLang] = useLocalStore<Languages>({
    defaultValue: DEFAULT_LANG,
    key: LANG_KEY,
    validator: isSupportedLang,
  })

  const changeLang = useCallback(
    (newLang: Languages) => {
      if (newLang === lang) return
      setLang(newLang)
    },
    [lang, setLang],
  )

  return { changeLang, lang }
}
