// ANIMATING ITEMS IN VIEW %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
export function inView() {
    const vItem = gsap.utils.toArray(".view")
    gsap.set(vItem, {opacity: 0})

    ScrollTrigger.batch(vItem, {
        start: "top 95%",
        trigger: vItem,
        onEnter: batch => gsap.to(batch, {
            opacity: 1,
            duration: 1,
            stagger: {
                amount: .2
            },
            ease: "power4.out"
        })
    });
}

// CLICK SCROLL ON MOBILES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
export function clickScroll() {
    if(isMobile()) {
        let button = document.querySelector(".scroll-to")
        button.addEventListener("click", function() {
            let thisId = button.dataset.scroll
            gsap.to(window, {duration: 1, ease: customEase, scrollTo: "#"+ thisId +""});

        })
    }
}

// PAGE TO PAGE ANIMATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
export function pageToPage() {
        const pageBgWrap = document.querySelector("#page-to-page"),
        redBg = document.querySelector(".red-bg"),
        greyBg = document.querySelector(".grey-bg")

        pageToPageAnim.to(redBg, {
            y:"0%",
            rotate: 0,
            onStart: () => {pageBgWrap.style.opacity = "1"},
            duration: 1.5,
            ease: customEase
        })
        pageToPageAnim.to(greyBg, {
            y:"0%",
            rotate: 0,
            duration: 1.5,
            ease: customEase,
            onComplete: ()=> {
                pageBgWrap.style.opacity = "0"
            }
        }, "-=1.35")


        return pageToPageAnim


}

// MOVE CURSOR CUSTOM %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
export function mouseCursor() {
    let mouseX = null
    let mouseY = null
    let ballX = null
    let ballY = null
    let ballSpeed = .17
    let cursor = document.querySelector("#customCursor")
    const moveArea = document.querySelectorAll(".cursorArea")

    moveArea.forEach(area => {
        area.addEventListener("mouseenter", function() {
            gsap.to(cursor, {
                scale: 1,
                duration: .4,
                ease: "power4"
            })
        })
        area.addEventListener("mouseleave", function() {
            gsap.to(cursor, {
                scale: 0,
                duration: .4,
                ease: "power4"
            })
        })
    })

    // CHECK SCROLL SPEED
    if(!isMobile()) {
        const mouseFollow = function () {
          if(mouseX) {
            if(!ballX) {
              ballX = mouseX
              ballY = mouseY
            }

            // DRAG FOLLOW
            let distX = mouseX - ballX
            let distY = mouseY - ballY

            ballX = ballX + (distX * ballSpeed)
            ballY = ballY + (distY * ballSpeed)

            gsap.to(cursor, {
              y: ballY,
              x: ballX,
              ease: "none",
              duration: .15
            })

          }
          requestAnimationFrame(mouseFollow)
        }
        mouseFollow()
        window.addEventListener("mousemove", function(event) {
            mouseX = event.clientX
            mouseY = event.clientY
        })
    }
}


// CONTACT PAGE FIXING NAMES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
export function contactScript() {
    if(!isMobile()) {
        let scrollHeight = (document.querySelector("#locations address:first-of-type").offsetHeight + document.querySelector("#locations address:nth-of-type(2)").offsetHeight + document.querySelector("#locations address:nth-of-type(3)").offsetHeight) - (document.querySelector(".scrolling-names").offsetHeight)
        let anim = gsap.timeline({
            scrollTrigger: {
                trigger: "#locations",
                start: "top -=120",
                end: () => "+=" + scrollHeight,
                pin: ".scrolling-names"
            }
        })
    }

    // makes sales bar draggable
    let salesItem = document.querySelectorAll("#sales article"),
        dragArea = document.querySelector("#sales > .op-grid"),
        itemWidth = salesItem[0].offsetWidth * salesItem.length + (window.innerWidth / 24 * 1.5),
        diff = itemWidth - document.querySelector("#sales").offsetWidth,
        val = window.innerWidth - diff,
        arrow = document.querySelector("#sales .arrow-btn"),
        slideVal = 1,
        newVal = 0

    if(!isMobile()) {
        // Make arrow click change the slide
        let items = document.querySelectorAll("#sales article div")
        let style = items[0].currentStyle || window.getComputedStyle(items[0])
        let margin = parseFloat(style.marginRight) * (items.length + 3)
        let tWidth = (items[0].offsetWidth * items.length) - window.innerWidth + margin

        Draggable.create(dragArea, {
            type: "x",
            bounds: {left: 0, width: val},
            inertia: true,
            onDragEnd: () => {
                slideVal = dragArea.getBoundingClientRect().left
                if(slideVal > 0) {
                    gsap.to(arrow, {
                        opacity: 1,
                        pointerEvents: "auto",
                        duration: .3,
                        ease: "power4"
                    })
                } else {
                    gsap.to(arrow, {
                        opacity: 0,
                        pointerEvents: "none",
                        duration: .3,
                        ease: "power4"
                    })
                }
                return slideVal
            }
        });

        if(slideVal > 0) {
            arrow.addEventListener("click", function() {
                gsap.to(dragArea, {
                    x: -tWidth,
                    duration: 1,
                    ease: "power3",
                    onComplete: () => {
                        gsap.to(arrow, {
                            opacity: 0,
                            pointerEvents: "none",
                            duration: .3,
                            ease: "power4"
                        })
                    }
                })  
            })
        } else {
            
        }

    }



}

// PRESS PAGE SCROLL ANIMATION =============================================================================================
export function pressScroll() {
    if(!isMobile()) {
        let title1 = document.querySelector(".press h1 > div:first-of-type")
        let title2 = document.querySelector(".press h1 > div:nth-of-type(2) ")

        let titleScroll = gsap.timeline({
            scrollTrigger: {
                trigger: contentTag,
                start: "top top",
                endTrigger: "#press-list",
                end: "top top",
                scrub: true
            }
        })
        titleScroll.to(title1, {
            xPercent: 25
        })
        titleScroll.to(title2, {
            xPercent: -24
        }, "<")
    }

    let curPage = 1
    const list = document.getElementById('press-list')
    const loadButtonContainer = document.querySelector("#loadMoreContainer")
    const loadButton = document.querySelector("#loadMore")
    let removeLoadMoreButtonOnNextClick = false

    function loadMoreAndPrepare() {
        const quantArticles = list.children.length
        const formData = { page: curPage + 1 }

        window.fetch('/press-articles', {
            method: 'post',
            body: JSON.stringify(formData),
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json; charset=UTF-8'
            }
        }).then((response) => {
            return response.json()
        }).then((res) => {
            if(res.pagination[res.pagination.length - 1].selected === 'selected') {
                removeLoadMoreButtonOnNextClick = true
            }

            if(res.status === 'sucess') {
                res.results.forEach(item => {
                    const article = document.createElement('article')
                    article.classList = 'first cursorArea new-added'
                    article.style.display = 'none'
                    article.innerHTML = `<a class="op-grid" href="${item.press_item.data.external_url}" target="_blank">
                                            <figure class="op-xl-5 op-sm-7">
                                                <img src="${item.press_item.data.thumb_image.url}&q=90" alt=${item.press_item.data.thumb_image.alt}>
                                            </figure>
                                            <div class="op-xl-7 op-sm-10 op-xs-12">
                                                <div>
                                                    <span class="f-20">${item.press_item.data.header}</span>
                                                    <h2 class="FontCopy f-30">${item.press_item.data.title}</h2>
                                                </div>
                                            </div>
                                        </a>`

                    list.insertBefore(article, loadButtonContainer);
                })
                curPage++
            }
        }).catch((error) => {
            console.log(error)
        })
    }

    function showLoaded() {
      if(removeLoadMoreButtonOnNextClick) loadButton.remove()

        gsap.utils.toArray('.new-added').forEach(article => {
            gsap.timeline()
              .set(article, { clearProps: 'display', y: 0 })
              .to(article, { opacity: 1, y: 0, duration: 1, ease: customEase,
                onComplete: () => article.classList.remove('new-added')
              })
        })

        mouseCursor()

        setTimeout(() => { ScrollTrigger.refresh() }, 100)
    }


    loadButton.addEventListener("click", function() {
        showLoaded()
        loadMoreAndPrepare()
    })

    loadMoreAndPrepare()
}

export function textDoubleHover() {
    
    if(!isMobile() && window.innerWidth > 1024) {
        let item = gsap.utils.toArray(".double-hover")

        item.forEach( dh => {
            let titCur = new SplitText(dh.querySelector("span:first-of-type") , { type: "chars" })
            let titNew = new SplitText(dh.querySelector("span:nth-of-type(2)"), { type: "chars" })
            
            gsap.set(titCur.chars, {yPercent: 0, transformOrigin: "top left"})
            gsap.set(titNew.chars, {yPercent: 22, scaleY: 0.2, transformOrigin: "bottom left"})

            dh.addEventListener("mouseenter", function() {
                gsap.to(titCur.chars, {
                    yPercent: -22,
                    scaleY: .2,
                    stagger: {
                        amount: .1
                    },
                    duration: .6,
                    ease: "power3"
                })
                gsap.to(titNew.chars, {
                    yPercent: 0,
                    scaleY: 1,
                    stagger: {
                        amount: .1
                    },
                    duration: .6,
                    ease: "power3"
                })
            })

            dh.addEventListener("mouseleave", function() {
                gsap.to(titCur.chars, {
                    yPercent: 0,
                    scaleY: 1,
                    stagger: {
                        amount: .1
                    },
                    duration: .6,
                    ease: "power3"
                })
                gsap.to(titNew.chars, {
                    yPercent: 22,
                    scaleY: .2,
                    stagger: {
                        amount: .1
                    },
                    duration: .6,
                    ease: "power3"
                })
            })

        })
    }
}
