<script setup>
import PublicErrorScreen from '~/components/shared/PublicErrorScreen.vue'
import { buildNotFoundPageSeo, useNotFoundContent } from '~/content/notFound'
import { buildPublicSeoLinks } from '~/utils/public-seo'

const props = defineProps({
  error: {
    type: Object,
    required: true,
  },
})

const { notFoundPage, notFoundUi } = useNotFoundContent({ registerLocaleSwitchContext: false })

const statusCode = computed(() => {
  const parsed = Number(props.error?.statusCode)
  return Number.isFinite(parsed) && parsed > 0 ? parsed : 500
})

const isNotFound = computed(() => statusCode.value === 404)

const resolvedTitle = computed(() => {
  if (isNotFound.value) {
    return notFoundUi.value.title || notFoundPage.value?.title || 'Page Not Found'
  }

  return String(props.error?.statusMessage || props.error?.message || '').trim() || 'Something went wrong'
})

const resolvedDescription = computed(() => {
  if (isNotFound.value) {
    return notFoundUi.value.description || notFoundPage.value?.excerpt || ''
  }

  return String(props.error?.data?.message || props.error?.statusMessage || '').trim()
})

const pageSeo = computed(() => {
  if (isNotFound.value) {
    return buildNotFoundPageSeo(notFoundPage.value)
  }

  return {
    title: resolvedTitle.value,
    description: resolvedDescription.value,
    ogTitle: resolvedTitle.value,
    ogDescription: resolvedDescription.value,
    ogImage: '',
    robots: 'noindex,nofollow',
    canonical: null,
    hreflang: [],
    xDefault: null,
  }
})

useSeoMeta({
  title: () => pageSeo.value.title,
  description: () => pageSeo.value.description,
  ogTitle: () => pageSeo.value.ogTitle,
  ogDescription: () => pageSeo.value.ogDescription,
  robots: () => pageSeo.value.robots,
})

useHead(() => ({
  link: buildPublicSeoLinks(pageSeo.value),
}))
</script>

<template>
  <PublicErrorScreen
    :status-code="statusCode"
    :title="resolvedTitle"
    :description="resolvedDescription"
  />
</template>
