import { useEffect } from 'react'
import { COMPANY_INFO } from '../lib/constants'
import type { Locale } from '../lib/i18n'

type PageMetaInput = {
  title: string
  description?: string
  locale: Locale
}

function setMetaTag(name: string, content: string) {
  const meta = document.querySelector(`meta[name="${name}"]`)
  if (meta) meta.setAttribute('content', content)
}

export function usePageMeta({ title, description, locale }: PageMetaInput) {
  useEffect(() => {
    const previousTitle = document.title
    const previousLang = document.documentElement.lang

    const suffix = locale === 'en' ? COMPANY_INFO.nameEn : COMPANY_INFO.name
    document.title = title ? `${title} - ${suffix}` : suffix

    document.documentElement.lang = locale === 'en' ? 'en' : 'zh-CN'

    if (description) {
      setMetaTag('description', description)
    }

    return () => {
      document.title = previousTitle
      document.documentElement.lang = previousLang
    }
  }, [description, locale, title])
}
