import { computed } from 'vue'
import { buildPublicLocaleSwitchContext, useRegisterPublicLocaleSwitchContext } from '~/composables/usePublicLocaleSwitchContext'
import { useContactContent } from '~/content/contact'
import { useResolvedPage } from '~/content/pages'
import { buildResolvedPageSeo, sortByOrder } from '~/content/utils'

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

export function useManageContent() {
  const managePage = useResolvedPage('manage')
  const { contactDepartments } = useContactContent()
  const localeSwitchContext = computed(() => buildPublicLocaleSwitchContext(managePage.value, { kind: 'list' }))

  useRegisterPublicLocaleSwitchContext(localeSwitchContext)

  const structuredContent = computed(() => managePage.value?.structuredContent || {})
  const ui = computed(() => structuredContent.value.ui || {})
  const lookup = computed(() => structuredContent.value.lookup || {})

  const manageHero = computed(() => ({
    badge: managePage.value?.subtitle || ui.value.heroBadge || '',
    title: managePage.value?.title || '',
    description: managePage.value?.excerpt || '',
  }))

  const manageLookup = computed(() => ({
    title: ui.value.formTitle || '',
    description: ui.value.formDescription || '',
    lookupError: ui.value.lookupError || '',
    submittingLabel: ui.value.submittingLabel || '',
    submitLabel: ui.value.submitLabel || '',
    secureTitle: ui.value.secureTitle || '',
    secureDescription: ui.value.secureDescription || '',
    capabilitiesHeading: ui.value.capabilitiesHeading || '',
    labels: lookup.value.labels || {},
    placeholders: lookup.value.placeholders || {},
  }))

  const manageCapabilities = computed(() => sortByOrder(structuredContent.value.capabilities || []))

  const manageSupport = computed(() => {
    const supportDepartment = contactDepartments.value.find((department) => String(department.name || '').toLowerCase().includes('support'))
      || contactDepartments.value[0]
      || null

    return {
      title: ui.value.supportTitle || '',
      description: ui.value.supportDescription || '',
      emailLabel: ui.value.supportEmailLabel || '',
      email: supportDepartment?.email || '',
      phone: supportDepartment?.phone || '',
    }
  })

  return {
    managePage,
    manageHero,
    manageLookup,
    manageCapabilities,
    manageSupport,
  }
}
