import { useHead, useRequestURL, useSeoMeta } from '#app'

type SeoInput = {
  title: string
  description: string
  path?: string
}

function getSiteOrigin() {
  if (import.meta.client) return window.location.origin
  try {
    return useRequestURL().origin
  } catch {
    return ''
  }
}

export function usePageSeo(input: SeoInput) {
  const origin = getSiteOrigin()
  const url = input.path && origin ? new URL(input.path, origin).toString() : undefined

  useSeoMeta({
    title: input.title,
    description: input.description,
    ogTitle: input.title,
    ogDescription: input.description,
    ogType: 'website',
    ...(url ? { ogUrl: url } : {}),
    twitterCard: 'summary_large_image'
  })

  if (url) {
    useHead({
      link: [{ rel: 'canonical', href: url }]
    })
  }
}
