import { useAsyncData } from '#imports'
import { computed, unref } from 'vue'
import { usePublicLocale } from '~/composables/usePublicLocale'
import {
  resolveLocalizedCollection,
  resolveLocalizedCollectionByKey,
  resolveLocalizedEntity,
} from '~/utils/localized-entities'
import { DEFAULT_PUBLIC_LOCALE, normalizePublicLocale } from '~/utils/public-locales'

function normalizePageLookupKey(value) {
  const raw = String(value || '').trim()
  return raw || '/'
}

const PAGE_INDEX_MODULES = {
  en: () => import('~/generated/site/pages/index/en'),
  ru: () => import('~/generated/site/pages/index/ru'),
  ka: () => import('~/generated/site/pages/index/ka'),
  de: () => import('~/generated/site/pages/index/de'),
  fr: () => import('~/generated/site/pages/index/fr'),
  es: () => import('~/generated/site/pages/index/es'),
  it: () => import('~/generated/site/pages/index/it'),
  pl: () => import('~/generated/site/pages/index/pl'),
  tr: () => import('~/generated/site/pages/index/tr'),
  ar: () => import('~/generated/site/pages/index/ar'),
  he: () => import('~/generated/site/pages/index/he'),
}

async function loadPageItems(locale = DEFAULT_PUBLIC_LOCALE) {
  const normalizedLocale = normalizePublicLocale(locale)
  const loadModule = PAGE_INDEX_MODULES[normalizedLocale] || PAGE_INDEX_MODULES[DEFAULT_PUBLIC_LOCALE]
  const { pageItems } = await loadModule()
  return Array.isArray(pageItems) ? pageItems : []
}

export {
  resolveLocalizedCollection,
  resolveLocalizedCollectionByKey,
  resolveLocalizedEntity,
}

export async function resolvePageBySlug(slug, locale = DEFAULT_PUBLIC_LOCALE) {
  const pageItems = await loadPageItems(locale)
  return resolveLocalizedEntity(pageItems, slug, locale)
}

export function useResolvedEntity(itemsRef, identifierRef) {
  const { locale } = usePublicLocale()

  return computed(() => resolveLocalizedEntity(unref(itemsRef), unref(identifierRef), locale.value))
}

export function useResolvedCollection(itemsRef) {
  const { locale } = usePublicLocale()

  return computed(() => resolveLocalizedCollection(unref(itemsRef), locale.value))
}

export function useResolvedPage(slugRef) {
  const { locale } = usePublicLocale()
  const normalizedSlug = computed(() => normalizePageLookupKey(unref(slugRef)))

  const { data } = useAsyncData(
    () => `public-page:${normalizePublicLocale(locale.value)}:${normalizedSlug.value}`,
    async () => {
      const pageItems = await loadPageItems(locale.value)
      return resolveLocalizedEntity(pageItems, normalizedSlug.value, locale.value)
    },
    {
      watch: [normalizedSlug, locale],
      default: () => null,
    },
  )

  return computed(() => data.value)
}
