import { useEffect } from 'react'

/**
 * Sets page <title> and og meta tags for each route.
 * Uses direct DOM mutation — no react-helmet required.
 */
export function usePageMeta(
  title: string,
  description?: string,
  imageUrl?: string,
) {
  useEffect(() => {
    if (title) document.title = title

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

    setMeta('og:title', title)
    setMeta('twitter:title', title, 'name')
    if (description) {
      setMeta('og:description', description)
      setMeta('description', description, 'name')
      setMeta('twitter:description', description, 'name')
    }
    if (imageUrl) {
      setMeta('og:image', imageUrl)
      setMeta('twitter:image', imageUrl, 'name')
    }
  }, [title, description, imageUrl])
}
