import React, { useLayoutEffect, useEffect, useState } from 'react'
// import '../styles.scss'

export interface TrackingProps {
  /** Array of values at which a scroll tracking event is added to the dataLayer. In percent of the page */
  borders?: number[]
  /** type of event */
  event?: string
  /** action of event */
  action?: string
  /** allow to fire tracking events more than on time */
  allowMulti?: boolean
  /** string to put before the border value in the tracking event f.e. content50 */

  contentPrefix?: string
}

export interface TrackingEventProps {
  gtm?: {
    uniqueEventId?: number
    start?: number
    element?: FormData[]
    elementClasses?: string
    elementTarget?: string
    elementId?: string
    elementUrl?: string
    triggers?: string
  }
  event: string
  event_action?: string
  event_label?: string
  eventCallback?: Function
  eventTimeout?: number
  article_id?: number
  article_title?: string
  article_type?: string
  category?: string
  pagetype?: string
  provider?: string
  publish_date?: number
  subcategory?: string
  type?: string
  uid?: string | undefined
}
interface WindowProps extends Window {
  dataLayer: TrackingEventProps[]
}
declare let window: WindowProps
/** Fires a tracking event if a waypoint enters the viewport. Not visible exept placeholder is forced. */
const bordersChecked: { [key: string]: boolean } = {}
export const ScrollTracking = ({
  borders = [25, 50, 75],
  event = 'Interactions',
  action = 'vertical-scroll',
  contentPrefix = 'content',
  allowMulti = false
}: TrackingProps) => {
  window.dataLayer = window.dataLayer || []

  const [currentPosition, setcurrentPosition] = useState<number>(0)
  const [lastPosition, setlastPosition] = useState<number>(0)

  function useWindowSize() {
    useLayoutEffect(() => {
      function checkPosition() {
        const pos =
          window.pageYOffset ||
          document.documentElement.scrollTop ||
          document.body.scrollTop
        const fullheight =
          (document.documentElement.scrollHeight ||
            document.body.scrollHeight) - window.innerHeight
        setcurrentPosition((pos * 100) / fullheight)
      }
      window.addEventListener('scroll', checkPosition)
      checkPosition()
      return () => window.removeEventListener('scroll', checkPosition)
    }, [])
  }
  useEffect(() => {
    setlastPosition(currentPosition)
    borders.forEach(b => {
      if (lastPosition < b && currentPosition > b) {
        if (!bordersChecked['b' + b] || allowMulti) {
          bordersChecked['b' + b] = true
          window.dataLayer.push({
            event: event,
            event_action: action,
            event_label: contentPrefix + b
          })
        }
      }
    })
  }, [currentPosition])
  const scrollPos = useWindowSize()
  return null
}
