import Router from 'next/router'
import React, { useCallback, useEffect } from 'react'
import ym, { YMInitializer } from 'react-yandex-metrika'

const WithYandexMetrika = (props) => {
  const { children } = props

  const enabled = process.env.NODE_ENV !== 'development'

  const hit = useCallback((url) => {
    if (enabled) {
      ym('hit', url)
    } else {
      console.log('%c[YandexMetrika](HIT)', 'color: orange', url)
    }
  }, [enabled])

  useEffect(() => {
    hit(window.location.pathname + window.location.search)
    Router.events.on('routeChangeComplete', hit)
  }, [hit])

  return (
    <>
      {enabled && (
        <YMInitializer
          accounts={[87671663]}
          options={{ webvisor: true, defer: true }}
          version='2'
        />
      )}
      {children}
    </>
  )
}

export default WithYandexMetrika
