import { useEffect } from 'react'

interface PageMeta {
  title: string
  description: string
  canonical: string
  ogTitle?: string
  ogDescription?: string
}

export function usePageMeta({ title, description, canonical, ogTitle, ogDescription }: PageMeta) {
  useEffect(() => {
    document.title = title

    setMeta('name', 'description', description)
    setMeta('property', 'og:title', ogTitle ?? title)
    setMeta('property', 'og:description', ogDescription ?? description)
    setMeta('property', 'og:url', canonical)
    setMeta('name', 'twitter:title', ogTitle ?? title)
    setMeta('name', 'twitter:description', ogDescription ?? description)
    setLink('canonical', canonical)
  }, [title, description, canonical, ogTitle, ogDescription])
}

function setMeta(attr: 'name' | 'property', key: string, value: string) {
  let el = document.querySelector<HTMLMetaElement>(`meta[${attr}="${key}"]`)
  if (!el) {
    el = document.createElement('meta')
    el.setAttribute(attr, key)
    document.head.appendChild(el)
  }
  el.setAttribute('content', value)
}

function setLink(rel: string, href: string) {
  let el = document.querySelector<HTMLLinkElement>(`link[rel="${rel}"]`)
  if (!el) {
    el = document.createElement('link')
    el.setAttribute('rel', rel)
    document.head.appendChild(el)
  }
  el.setAttribute('href', href)
}
