const SITE = 'https://valueerp.net'
const SUPPORTED = ['en', 'ar']

const DEFAULTS = {
  en: {
    siteName: 'ValuePlus',
    titleBase: 'ValuePlus',
    description: 'ValuePlus helps you discover smarter value decisions across platforms.',
    dir: 'ltr',
    ogLocale: 'en_US',
  },
  ar: {
    siteName: 'ValuePlus',
    titleBase: 'ValuePlus',
    description: 'ValuePlus يساعدك على اتخاذ قرارات أفضل من حيث القيمة عبر المنصات المختلفة.',
    dir: 'rtl',
    ogLocale: 'ar_AR',
  },
}

function getLang(to) {
  const lang = to.params?.lang
  return SUPPORTED.includes(lang) ? lang : 'en'
}

function pickLang(value, lang) {
  if (!value) return ''
  if (typeof value === 'string') return value
  return value[lang] || value.en || ''
}

function abs(pathOrUrl) {
  if (!pathOrUrl) return SITE
  if (pathOrUrl.startsWith('http')) return pathOrUrl
  return `${SITE}${pathOrUrl.startsWith('/') ? '' : '/'}${pathOrUrl}`
}

function trimTrailingSlash(url) {
  return url.endsWith('/') && url !== `${SITE}/` ? url.slice(0, -1) : url
}

export function installSeoHook(router, head) {
  // In some versions head.push returns { dispose() }, in others it may return a function.
  let headEntry = null

  const disposeEntry = () => {
    if (!headEntry) return
    // handle both shapes safely
    if (typeof headEntry === 'function') headEntry()
    else if (typeof headEntry.dispose === 'function') headEntry.dispose()
    headEntry = null
  }

  const apply = (to) => {
    const lang = getLang(to)
    const defaults = DEFAULTS[lang] || DEFAULTS.en
    const seo = to.meta?.seo || {}

    const pageTitle = pickLang(seo.title, lang)
    const title = pageTitle ? `${pageTitle} | ${defaults.titleBase}` : defaults.titleBase
    const description = pickLang(seo.description, lang) || defaults.description

    const canonical = trimTrailingSlash(abs(router.resolve(to).fullPath))

    let hrefEn = `${SITE}/en/home`
    let hrefAr = `${SITE}/ar/home`

    if (to.name) {
      hrefEn = trimTrailingSlash(
        abs(router.resolve({ name: to.name, params: { ...to.params, lang: 'en' }, query: to.query }).fullPath)
      )
      hrefAr = trimTrailingSlash(
        abs(router.resolve({ name: to.name, params: { ...to.params, lang: 'ar' }, query: to.query }).fullPath)
      )
    }

    const ogImage = abs(seo.image || '/favicon.svg')
    const robots = seo.robots || 'index, follow'
    const xDefault = hrefEn

    // ✅ remove the previous head entry for the previous route
    disposeEntry()

    // ✅ push a new head entry and keep its handle
    headEntry = head.push({
      htmlAttrs: { lang, dir: defaults.dir },
      title,

      link: [
        { rel: 'canonical', href: canonical, key: 'canonical' },
        { rel: 'alternate', hreflang: 'en', href: hrefEn, key: 'alternate-en' },
        { rel: 'alternate', hreflang: 'ar', href: hrefAr, key: 'alternate-ar' },
        { rel: 'alternate', hreflang: 'x-default', href: xDefault, key: 'alternate-x-default' },
      ],

      meta: [
        { name: 'robots', content: robots, key: 'robots' },
        { name: 'description', content: description, key: 'description' },

        { itemprop: 'name', content: defaults.siteName, key: 'itemprop:name' },
        { itemprop: 'description', content: description, key: 'itemprop:description' },
        { itemprop: 'image', content: ogImage, key: 'itemprop:image' },

        { property: 'og:url', content: canonical, key: 'og:url' },
        { property: 'og:type', content: 'website', key: 'og:type' },
        { property: 'og:site_name', content: defaults.siteName, key: 'og:site_name' },
        { property: 'og:title', content: title, key: 'og:title' },
        { property: 'og:description', content: description, key: 'og:description' },
        { property: 'og:image', content: ogImage, key: 'og:image' },
        { property: 'og:locale', content: defaults.ogLocale, key: 'og:locale' },

        { name: 'twitter:card', content: 'summary_large_image', key: 'twitter:card' },
        { name: 'twitter:title', content: title, key: 'twitter:title' },
        { name: 'twitter:description', content: description, key: 'twitter:description' },
        { name: 'twitter:image', content: ogImage, key: 'twitter:image' },
      ],
    })
  }

  router.isReady().then(() => apply(router.currentRoute.value))
  router.afterEach((to) => apply(to))
}
