import { DEFAULT_PUBLIC_LOCALE, normalizePublicLocale } from '~/utils/public-locales'
import { loadOffersLocaleExportExact } from '~/content/offers-export'

const HOME_PAGE_MODULES = import.meta.glob('../generated/site/home/page/*.js')
const HOME_BLOCK_MODULES = import.meta.glob('../generated/site/home/blocks/*.js')
const HOME_ARTICLE_MODULES = import.meta.glob('../generated/site/home/articles/*.js')
const HOME_VEHICLE_MODULES = import.meta.glob('../generated/site/home/vehicles/*.js')
const HAS_HOME_SPLIT_EXPORT = Object.keys(HOME_PAGE_MODULES).length > 0

const homeLocaleExportCache = new Map()

function homeModuleLoader(modules, section, locale) {
  const normalizedLocale = normalizePublicLocale(locale)
  return modules[`../generated/site/home/${section}/${normalizedLocale}.js`]
    || modules[`../generated/site/home/${section}/${DEFAULT_PUBLIC_LOCALE}.js`]
    || null
}

async function loadHomeSplitSection(modules, section, exportName, locale, fallbackValue) {
  const loader = homeModuleLoader(modules, section, locale)

  if (!loader) {
    return fallbackValue
  }

  const module = await loader()
  return module?.[exportName] ?? fallbackValue
}

async function loadSplitHomeLocaleExport(locale) {
  const normalizedLocale = normalizePublicLocale(locale)
  const homePage = await loadHomeSplitSection(
    HOME_PAGE_MODULES,
    'page',
    'homePage',
    normalizedLocale,
    null,
  )

  if (!homePage) {
    return null
  }

  const [homeBlocks, featuredOffersLocale, featuredOffersEn, featuredArticles, featuredVehicles] = await Promise.all([
    loadHomeSplitSection(HOME_BLOCK_MODULES, 'blocks', 'homeBlocks', normalizedLocale, []),
    loadOffersLocaleExportExact(normalizedLocale, []),
    normalizedLocale === DEFAULT_PUBLIC_LOCALE
      ? Promise.resolve([])
      : loadOffersLocaleExportExact(DEFAULT_PUBLIC_LOCALE, []),
    loadHomeSplitSection(HOME_ARTICLE_MODULES, 'articles', 'featuredArticles', normalizedLocale, []),
    loadHomeSplitSection(HOME_VEHICLE_MODULES, 'vehicles', 'featuredVehicles', normalizedLocale, []),
  ])

  return {
    homePage,
    homeBlocks,
    featuredOffers: [...(Array.isArray(featuredOffersLocale) ? featuredOffersLocale : []), ...(Array.isArray(featuredOffersEn) ? featuredOffersEn : [])]
      .filter((item, index, items) => {
        const key = String(item?.contentKey || item?.slug || item?.id || '').trim()

        if (!key) {
          return false
        }

        return items.findIndex((candidate) => String(candidate?.contentKey || candidate?.slug || candidate?.id || '').trim() === key) === index
      }),
    featuredArticles,
    featuredVehicles,
  }
}

export async function loadHomeLocaleExport(locale = DEFAULT_PUBLIC_LOCALE) {
  const normalizedLocale = normalizePublicLocale(locale)

  if (!homeLocaleExportCache.has(normalizedLocale)) {
    homeLocaleExportCache.set(normalizedLocale, (async () => {
      if (!HAS_HOME_SPLIT_EXPORT) {
        return {
          homePage: null,
          homeBlocks: [],
          featuredOffers: [],
          featuredArticles: [],
          featuredVehicles: [],
        }
      }

      return loadSplitHomeLocaleExport(normalizedLocale)
    })())
  }

  return homeLocaleExportCache.get(normalizedLocale)
}

export async function loadHomePage(locale = DEFAULT_PUBLIC_LOCALE) {
  const payload = await loadHomeLocaleExport(locale)
  return payload?.homePage || null
}

export async function loadHomeSearchForm(locale = DEFAULT_PUBLIC_LOCALE) {
  const homePage = await loadHomePage(locale)
  return homePage?.structuredContent?.hero?.searchForm || {}
}

export async function loadHomeRequestStatus(locale = DEFAULT_PUBLIC_LOCALE) {
  const homePage = await loadHomePage(locale)
  return homePage?.structuredContent?.hero?.requestStatus || {}
}
