import { computed } from 'vue'

import { messages } from 'src/i18n/messages'
import { DEFAULT_LOCALE } from 'src/i18n/languages'
import { useLocaleStore } from 'src/stores/localeStore'
import { useRuntimeTranslationStore } from 'src/stores/runtimeTranslationStore'

function lookup(obj, path) {
  return String(path || '')
    .split('.')
    .filter(Boolean)
    .reduce((acc, key) => (acc && acc[key] != null ? acc[key] : undefined), obj)
}

export function useI18n() {
  const localeStore = useLocaleStore()
  const runtimeTranslations = useRuntimeTranslationStore()

  const currentLocale = computed(() => localeStore.locale)

  function fallbackLocales(locale) {
    const normalized = String(locale || '').toLowerCase()
    if (normalized === 'tr') return ['tr']
    if (normalized === 'en') return ['en', 'tr']
    return [normalized, 'en', 'tr']
  }

  function t(key) {
    const runtimeValue = runtimeTranslations.translateKey(key)
    if (runtimeValue && runtimeValue !== key) {
      return runtimeValue
    }

    for (const locale of fallbackLocales(currentLocale.value)) {
      const val = lookup(messages[locale] || {}, key)
      if (val != null) return val
    }

    const byDefault = lookup(messages[DEFAULT_LOCALE] || {}, key)
    if (byDefault != null) return byDefault

    return key
  }

  return {
    locale: currentLocale,
    t
  }
}
