import {gsap, Power1} from 'gsap'
export default (() => {
    const activatePopup = document.querySelector('[data-activate-popup]')
    if(activatePopup) {
        const getCookieValue = (name) => (
            document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)') &&
            document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)').pop() || ''
        )

        let visible = true

        const popup = document.querySelector('[data-popup].popup')
        const autoclose = popup.dataset.autoclose
        const howLong = Number(popup.dataset.howlong)
    
        const closer = popup.querySelector('.popup-closer')
        const opener = document.querySelector('[data-popup].popup-opener')

        const timelineOpener = gsap.timeline()

        timelineOpener.to(opener, {
            y: opener.clientHeight,
            ease: Power1.easeOut,
            duration: 0.3,
        })

        timelineOpener.pause()

        const cookieValue = getCookieValue('viewed_popup')

        if (cookieValue != 'false') {
          popup.classList.add('opened')
    
          if(autoclose == true) {
              setTimeout(() => {
                  popup.classList.remove('opened')
              }, howLong);
          }
        }
    
        opener.addEventListener('click', () => {
          popup.classList.add('opened')

          timelineOpener.restart()
        })

        window.addEventListener('scroll', () => {
          if ((window.innerHeight + window.scrollY) > document.body.offsetHeight - 50) {
            if(visible == true) {
              timelineOpener.play()
              timelineOpener.eventCallback('onComplete', () => {
                visible = false
              })
            }
          } else if (popup.classList.contains('opened') == false) {
              timelineOpener.reverse()
              timelineOpener.eventCallback('onReverseComplete', () => {
                visible = true
              })
          }
        })
    
        closer.addEventListener('click', () => {
          document.cookie = 'viewed_popup=false'
          popup.classList.remove('opened')
          timelineOpener.reverse()
        })
    }
})()
