import { onMounted } from 'vue'
import type { Router } from 'vue-router'
import { CONFIG } from '../lib/config'

declare global {
  interface Window { _paq?: Array<unknown[]> }
}

export function useMatomo(router: Router) {
  onMounted(() => {
    const _paq = (window._paq = window._paq || [])
    _paq.push(['enableLinkTracking'])
    const u = CONFIG.matomoUrl
    _paq.push(['setTrackerUrl', u + 'matomo.php'])
    _paq.push(['setSiteId', CONFIG.matomoSiteId])
    _paq.push(['setCustomUrl', window.location.href])
    _paq.push(['setDocumentTitle', document.title])
    _paq.push(['trackPageView'])
    const d = document
    const g = d.createElement('script')
    const s = d.getElementsByTagName('script')[0]
    g.async = true
    g.src = u + 'matomo.js'
    s.parentNode!.insertBefore(g, s)
  })

  router.beforeEach((_to, from) => {
    const _paq = window._paq
    if (_paq && from.fullPath) {
      _paq.push(['setReferrerUrl', window.location.origin + from.fullPath])
    }
  })

  router.afterEach((to) => {
    const _paq = window._paq
    if (!_paq) return
    _paq.push(['setCustomUrl', window.location.origin + to.fullPath])
    setTimeout(() => {
      _paq.push(['setDocumentTitle', document.title])
      _paq.push(['trackPageView'])
    }, 0)
  })
}
