import React from 'react'
import { Waypoint } from 'react-waypoint'
import '../styles.scss'

export interface TrackingProps {
  /** Event-Category */
  evnt?: string | 'below' | 'above'
  /** Event-Type */
  action?: string
  /** Event-Label */
  label?: string
  /** Direction for entering the viewport */
  enterFrom?: 'below' | 'above'
  /** Forces the placeholder to be shown */
  placeholder?: boolean
}
export interface ScrollEventsProps {
  currentPosition: string
  event: Event
  previousPosition: string
  viewportBottom: number
  viewportTop: number
  waypointBottom: number
  waypointTop: number
}
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. */

export const ScrollTracking = ({
  evnt = 'Interactions',
  action = 'vertical-scroll',
  label,
  enterFrom = 'below',
  placeholder = false
}: TrackingProps) => {
  window.dataLayer = window.dataLayer || []
  return (
    <>
      {(placeholder || !label || label === '') && (
        <div className='cbPlaceholder'>
          {placeholder && label
            ? 'ScrollTracking is triggered right here. – Label: ' + label
            : 'ScrollTracking will be triggered here, if you provide a label.'}
        </div>
      )}
      {label && (
        <Waypoint
          onEnter={(event: Waypoint.CallbackArgs) => {
            if (
              // (@ts-ignore
              event.previousPosition === Waypoint[enterFrom] &&
              event.currentPosition === Waypoint.inside
            ) {
              window.dataLayer.push({
                event: evnt,
                event_action: action,
                event_label: label
              })
            }
          }}
        />
      )}
    </>
  )
}
ScrollTracking.defaultProps = {
  evnt: 'Interactions',
  action: 'vertical-scroll',
  enterFrom: 'below'
}
