import { normalizePublicLocale } from '~/utils/public-locales'
import publicUiEn from '~/i18n/ui/en'
import publicUiFr from '~/i18n/ui/fr'
import publicUiEs from '~/i18n/ui/es'
import publicUiRu from '~/i18n/ui/ru'
import publicUiDe from '~/i18n/ui/de'
import publicUiKa from '~/i18n/ui/ka'
import publicUiIt from '~/i18n/ui/it'
import publicUiAr from '~/i18n/ui/ar'
import publicUiHe from '~/i18n/ui/he'
import publicUiPl from '~/i18n/ui/pl'
import publicUiTr from '~/i18n/ui/tr'

const publicUiBase = publicUiEn

const publicUiOverrides = {
  fr: publicUiFr,
  es: publicUiEs,
  ru: publicUiRu,
  de: publicUiDe,
  ka: publicUiKa,
  it: publicUiIt,
  ar: publicUiAr,
  he: publicUiHe,
  pl: publicUiPl,
  tr: publicUiTr,
}

function isObject(value) {
  return value && typeof value === 'object' && !Array.isArray(value)
}

function deepMerge(base, override) {
  if (!isObject(base)) {
    return override ?? base
  }

  const result = { ...base }

  Object.entries(override || {}).forEach(([key, value]) => {
    if (isObject(value) && isObject(base[key])) {
      result[key] = deepMerge(base[key], value)
      return
    }

    result[key] = value
  })

  return result
}

function getByPath(source, path) {
  return String(path || '')
    .split('.')
    .filter(Boolean)
    .reduce((accumulator, segment) => (accumulator == null ? undefined : accumulator[segment]), source)
}

export function resolvePublicUiCopy(locale) {
  const normalizedLocale = normalizePublicLocale(locale)
  return deepMerge(publicUiBase, publicUiOverrides[normalizedLocale] || {})
}

export function resolvePublicUiValue(locale, path, fallback = '') {
  const value = getByPath(resolvePublicUiCopy(locale), path)
  return value === undefined || value === null || value === '' ? fallback : value
}
