import { defineStore } from 'pinia'
import { ref } from 'vue'

import api from 'src/services/api'
import { DEFAULT_LOCALE, normalizeLocale } from 'src/i18n/languages'

function normalizeRuntimeText (value) {
  return String(value || '').trim().replace(/\s+/g, ' ')
}

export const useRuntimeTranslationStore = defineStore('runtimeTranslation', () => {
  const locale = ref(DEFAULT_LOCALE)
  const byKey = ref({})
  const byText = ref({})
  const loading = ref(false)
  const loadedLocales = ref({})
  const version = ref(0)

  async function loadLocale (nextLocale, options = {}) {
    const normalized = normalizeLocale(nextLocale)
    const force = Boolean(options?.force)
    locale.value = normalized

    if (!force && loadedLocales.value[normalized]) {
      byKey.value = loadedLocales.value[normalized].byKey
      byText.value = loadedLocales.value[normalized].byText
      version.value += 1
      return true
    }

    loading.value = true
    try {
      const res = await api.get('/language/translations/runtime', {
        params: { lang: normalized },
        timeout: 180000
      })
      const payload = res?.data || {}
      const nextByKey = payload?.by_key && typeof payload.by_key === 'object' ? payload.by_key : {}
      const nextByTextRaw = payload?.by_text && typeof payload.by_text === 'object' ? payload.by_text : {}
      const nextByText = {}
      for (const [source, translated] of Object.entries(nextByTextRaw)) {
        const sourceKey = normalizeRuntimeText(source)
        const display = normalizeRuntimeText(translated)
        if (sourceKey && display) nextByText[sourceKey] = display
      }

      loadedLocales.value = {
        ...loadedLocales.value,
        [normalized]: {
          byKey: nextByKey,
          byText: nextByText
        }
      }
      byKey.value = nextByKey
      byText.value = nextByText
      version.value += 1
      return true
    } catch (err) {
      console.warn('[runtime-i18n] dictionary load failed', normalized, err)
      byKey.value = {}
      byText.value = {}
      version.value += 1
      return false
    } finally {
      loading.value = false
    }
  }

  function translateKey (key) {
    const raw = String(key || '').trim()
    if (!raw) return ''
    return byKey.value[raw] || raw
  }

  function translateText (text) {
    const normalized = normalizeRuntimeText(text)
    if (!normalized) return ''
    return byText.value[normalized] || normalized
  }

  return {
    locale,
    byKey,
    byText,
    loading,
    version,
    loadLocale,
    translateKey,
    translateText
  }
})
