import { computed } from 'vue'
import { buildPublicLocaleSwitchContext, useRegisterPublicLocaleSwitchContext } from '~/composables/usePublicLocaleSwitchContext'
import { useResolvedPage } from '~/content/pages'
import { buildResolvedPageSeo } from '~/content/utils'
import { usePublicLocale } from '~/composables/usePublicLocale'
import { normalizePublicInternalPath } from '~/utils/public-routes'

export function buildHelpPageSeo(page, origin = '') {
  return buildResolvedPageSeo(page, origin, {
    ogImage: page?.heroImage || page?.featuredImage || '',
  })
}

export function useHelpContent() {
  const helpContentPage = useResolvedPage('help')
  const { locale } = usePublicLocale()
  const localeSwitchContext = computed(() => buildPublicLocaleSwitchContext(helpContentPage.value, { kind: 'list' }))

  useRegisterPublicLocaleSwitchContext(localeSwitchContext)

  const helpUi = computed(() => ({
    searchPlaceholder: helpContentPage.value?.structuredContent?.ui?.searchPlaceholder,
    articlesHeading: helpContentPage.value?.structuredContent?.ui?.articlesHeading,
    emptySearchState: helpContentPage.value?.structuredContent?.ui?.emptySearchState,
    supportTitle: helpContentPage.value?.structuredContent?.supportCard?.title,
    supportDescription: helpContentPage.value?.structuredContent?.supportCard?.description,
    supportCtaLabel: helpContentPage.value?.structuredContent?.supportCard?.ctaLabel || helpContentPage.value?.cta?.label,
    supportCtaUrl: normalizePublicInternalPath(helpContentPage.value?.cta?.url, locale.value),
  }))

  const helpCategories = computed(() => [...(helpContentPage.value?.structuredContent?.categories || [])]
    .sort((left, right) => (left.sortOrder || 0) - (right.sortOrder || 0))
    .map((category) => ({
      ...category,
      link: normalizePublicInternalPath(category?.link, locale.value),
    })))

  const helpTopicLinks = computed(() => [...(helpContentPage.value?.structuredContent?.topicLinks || [])]
    .sort((left, right) => (left.sortOrder || 0) - (right.sortOrder || 0))
    .map((topic) => ({
      ...topic,
      link: normalizePublicInternalPath(topic?.link, locale.value),
    })))

  return {
    helpContentPage,
    helpUi,
    helpCategories,
    helpTopicLinks,
  }
}
