import { computed } from 'vue'
import { buildPublicLocaleSwitchContext, useRegisterPublicLocaleSwitchContext } from '~/composables/usePublicLocaleSwitchContext'
import { usePublicLocale } from '~/composables/usePublicLocale'
import { useResolvedPage } from '~/content/pages'
import { buildResolvedPageSeo, formatContentDate, replaceDateToken, sortByOrder } from '~/content/utils'
import { DEFAULT_PUBLIC_LOCALE, normalizePublicLocale, toPublicLocaleCode } from '~/utils/public-locales'

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

function buildLegalFooterCopy(template, dateLabel) {
  const resolvedTemplate = String(template || '')
  const resolvedDate = String(dateLabel || '')
  let footerCopy = replaceDateToken(resolvedTemplate, resolvedDate)

  if (resolvedDate && resolvedDate.endsWith('.') && footerCopy.includes(`${resolvedDate}.`)) {
    footerCopy = footerCopy.replace(`${resolvedDate}.`, resolvedDate)
  }

  return footerCopy
}

function buildLegalContent(page, locale = DEFAULT_PUBLIC_LOCALE) {
  const structuredContent = page?.structuredContent || {}
  const ui = structuredContent.ui || {}
  const publishedLabel = formatContentDate(page?.publishedAt || page?.seo?.lastModified, toPublicLocaleCode(normalizePublicLocale(locale)))
  const isPublished = Boolean(page?.publishedAt)
  const footerTemplate = isPublished ? ui.footerPublished : ui.footerDraft

  return {
    title: page?.title || '',
    subtitle: page?.subtitle || '',
    excerpt: page?.excerpt || '',
    intro: structuredContent.intro || '',
    sections: sortByOrder(structuredContent.sections || []),
    lastUpdatedLabel: ui.lastUpdatedLabel || '',
    lastUpdatedValue: publishedLabel,
    footerCopy: buildLegalFooterCopy(footerTemplate, publishedLabel),
    emptyIntro: ui.emptyIntro || '',
  }
}

export function useLegalContent(slug) {
  const { locale } = usePublicLocale()
  const page = useResolvedPage(slug)
  const localeSwitchContext = computed(() => buildPublicLocaleSwitchContext(page.value, { kind: 'list' }))

  useRegisterPublicLocaleSwitchContext(localeSwitchContext)
  const content = computed(() => buildLegalContent(page.value, locale.value))

  return {
    page,
    content,
  }
}

export function useTermsContent() {
  return useLegalContent('terms')
}

export function usePrivacyContent() {
  return useLegalContent('privacy')
}
