import './jquery-3.7.1.min.js';
import {gsap, TimelineMax} from 'gsap';
import {ScrollTrigger} from "gsap/ScrollTrigger";
import {ScrollSmoother} from "gsap/ScrollSmoother";
import './owl.carousel.min.js';

alert()

gsap.registerPlugin(ScrollTrigger, ScrollSmoother);
var scrollSmoother;

function generateScrollSmoother(smooth=.75, speed=1, effects=true, smoothTouch=.1){
    if (scrollSmoother){
        scrollSmoother.kill();
    }
    scrollSmoother = ScrollSmoother.create({
            smooth: smooth,
            speed: speed,
            effects: effects,
            smoothTouch: smoothTouch
        }
    );
}

generateScrollSmoother();
scrollSmoother.scrollTop(0);
document.addEventListener('DOMContentLoaded', ()=>{scrollSmoother.scrollTop(0)})

// Resize Handler
let brandsScrollerStart = "top top";
function resize(){
    let width = window.innerWidth;
    let height = window.innerHeight;
    if (width <= 768){
        brandsScrollerStart = "100 top"
    }
    if ((width <= 1024)){
        if (scrollSmoother.vars.smooth != .1){
            generateScrollSmoother(.1);
        }
    }else if (scrollSmoother.vars.smooth == .1){
        generateScrollSmoother();
    }
}
resize();
window.onresize = resize;


// Nav Cursor
const navCursor = document.querySelector(".nav-cursor");
let navCursorPositionSet = false;
if (navCursor){
    function setNavCursorPosition(element){
        if (!element){return}
        let bounding = element.getBoundingClientRect();
        let func = gsap.to;
        if (!navCursorPositionSet){func = gsap.set}
        func(navCursor, {x: bounding.x - parseInt($(".global-header").css("padding-left").replace("px", "")), width: bounding.width, duration: .25})
    }
    setNavCursorPosition(document.querySelector(".global-nav-links li"))
    document.querySelectorAll(".global-nav-links li > a").forEach((navItem)=>{
        if(navItem.matches(':hover')){setNavCursorPosition(event.currentTarget.parentElement)}
        navItem.addEventListener('mouseover', (event)=>{
            setNavCursorPosition(event.currentTarget.parentElement);
            navCursorPositionSet = true;
        })
        if(navItem.parentElement.querySelector(".nav-dropdown-wrapper")){
            navItem.addEventListener('click', (event)=>{
                let doesContain = event.currentTarget.classList.contains('active');
                $('.global-nav-links > li > a.active').removeClass("active");
                if (!doesContain){
                    event.currentTarget.classList.add('active');
                }
            })
        }
    });

    document.querySelector(".nav-dropdown-close-wrapper").addEventListener("click", (event)=>{
        $('.global-nav-links > li > a.active').removeClass("active");
    })
    document.querySelector(".global-nav-links").addEventListener('mouseleave', (event)=>{
        let activeEl = event.currentTarget.querySelector('li a.active');
        if(activeEl){
            setNavCursorPosition(activeEl)
        }
    })
    $(".nav-dropdown-wrapper").on("mouseover",(event)=>{setNavCursorPosition(event.currentTarget.parentElement)})

}


// Intro
const header = document.querySelector("header");
const introTop = document.querySelector(".intro-top");
const introImg = document.querySelector(".intro-img");
if (introImg){
    ScrollTrigger.create({
        trigger: ".main-section",
        pin: false,
        start: 'top top',
        end: '+=400',
        scrub: 1,
        onUpdate: (self)=>{
            if (window.innerWidth < 1024){
                gsap.set(introImg, {width: "98%", y: 0})
                gsap.set(introTop, {y: 0});
                return;
            }
            if (self.progress > 0.05){
                header.classList.add('active');
            }else{
                header.classList.remove('active');
            }
            let yIntro = ( introTop.getBoundingClientRect().height * self.progress );
            let y = -( 60 * self.progress );
            let width = (98 + ( 2 * self.progress ))+"%";
            let radius = 80 - ( 80 * self.progress )
            gsap.set(introImg, {width: width, y: y, borderTopLeftRadius: radius, borderTopRightRadius: radius})
            gsap.set(introTop, {y: yIntro})
        },
        onLeaveBack: ()=>{header.classList.remove('active');}
    });
}


// Footer
const footer = document.querySelector("footer");
const footerPadding = document.querySelector(".footer-padding");
let footerHeight = footer.getBoundingClientRect().height;
const mainSection = document.querySelector(".main-section");
let mainSectionHeight = mainSection.getBoundingClientRect().height;
const smoothContent = document.querySelector("#smooth-content");
const lastSection = document.querySelector(".main-section > .content-section:last-of-type");
$(footer).css({
    "position": "absolute",
    "bottom": footerHeight,
    "z-index": -1
})
$(lastSection).css({
    "border-bottom-left-radius": 80,
    "border-bottom-right-radius": 80
})
$(footerPadding).css({
    "padding-bottom": footerHeight,
    "pointer-events": "none"
})
var footerTrigger;
let isPlaying = false;
footerTrigger = ScrollTrigger.create({
    trigger: footer,
    start: footerHeight +" bottom",
    end: "+="+footerHeight,
    onUpdate: (self)=>{
        isPlaying = true;
        gsap.to(footer, {duration: .05, bottom: footerHeight - ( footerHeight * self.progress )})
        gsap.to(mainSection, {duration: .05, scale: 1 - (.05 * self.progress), y: (mainSection.getBoundingClientRect().height * .0275 * self.progress)})
    },
    onComplete: ()=>{
        isPlaying = false;
    } ,
    onReverseComplete: ()=>{
        isPlaying = false;
    },
    onLeaveBack: ()=>{
        isPlaying = false;
    }
})

var observer = new ResizeObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        if (true){
            footerTrigger.refresh();
        }
    });
});

observer.observe(mainSection);


// Fade in on scroll
let projectContainer = document.querySelector(".project-container");
if (projectContainer){
var mainTimeline = new TimelineMax();
    let tl = gsap.timeline({
        scrollTrigger: {
            trigger: ".project-container",
            start: '100 bottom',
            end: "+=500",
            scrub: 1
        }
    });
    document.querySelectorAll(".project-grid-item").forEach((item=>{
        tl.from(item, .01, {alpha: 0, opacity: 0, y: 50, ease: "Power1.out"})
        mainTimeline.add(tl, '-=0.1');
    }));
}


// Skip Buttons
function initalizeSkipButton(skipBtn){
    let data = skipBtn.getAttribute('data-skip');
    if (data){
        skipBtn.addEventListener('click', ()=>{
            let height = document.querySelector(data).getBoundingClientRect().height;
            let y = 80;
            if (height <= window.innerHeight){
                y = (window.innerHeight - height) / 2;
            }
            scrollSmoother.scrollTo(data, 10, "-=" + y)
        })
    }
    
}
document.querySelectorAll('.skip-button').forEach(initalizeSkipButton)


// Dropdown Boxes
function expandMenu(el, height, duration = .25) {
    $(el).removeAttr("style");
    gsap.timeline()
    .set(el, {height: "auto", width: "auto"})
    .from(el, {
        height: height,
        duration: duration,
        ease: "power1.out"
    })
}

function closeMenu(el, height, duration = .25) {
    $(el).removeAttr("style");
    gsap.timeline()
    .set(el, {height: "auto", width: "auto"})
    .to(el, {
        height: height,
        duration: duration,
        ease: "power1.out"
    })
}

document.querySelectorAll('.dd-box-container').forEach((container)=>{
    container.querySelectorAll('.dd-box-item').forEach((el)=>{
        el.addEventListener("click", (event)=>{
            let activeElement = container.querySelector('.dd-box-item.active');
            if(activeElement){
                activeElement.classList.remove("active");
                closeMenu(activeElement.querySelector(".dd-box-content"), 24)
            }
            if (!(activeElement == event.currentTarget) || !(activeElement)){
                el.classList.add("active");
                expandMenu(event.currentTarget.querySelector(".dd-box-content"), 24)
            }
        })
    })
});


// Popup
function initalizePopup(popupWrapper){
    let closeEl = popupWrapper.querySelector(".popup-close");
    let popup = popupWrapper.querySelector(".popup");
    gsap.from(popup, {opacity: 0, y: 150, ease: "Power4.inOut", duration: .375});
    closeEl.addEventListener("click", (event)=>{
        gsap.to(popup, {opacity: 0, y: 150, ease: "Power4.inOut", duration: .375, onComplete: ()=>{popupWrapper.remove();}});
    })
    let owl = popupWrapper.querySelector(".owl-carousel");
    if (owl){initalizeOwlCarousel(owl)}
    let owlNav = popupWrapper.querySelector(".popup-slider-navigator");
    if (owlNav){
        owlNavigator(owlNav.querySelector("[data-owl-next]"), "next");
        owlNavigator(owlNav.querySelector("[data-owl-prev]"), "prev");
    }
    $(popupWrapper).find(".input-select").each((index, item)=>{
        initalizeSelectInput(item);
        initalizeActivate(item);
        initalizeFocusoutInactive(item);
    })
}
document.addEventListener("DOMContentLoaded", ()=>{
    document.querySelectorAll(".popup-wrapper").forEach(initalizePopup);
})


// Owl Carousels
function updateSlider(event){
    let count = event.item.count;
    let index = Math.max(event.item.index, 2);
    document.querySelector(".page-indicator").innerHTML = (index - 1) + "/" + (count);
}

function initalizeOwlCarousel(carouselEl){
    let data = carouselEl.getAttribute('data-carousel');
    if (data){
        let options = JSON.parse(data.replaceAll("'", '"'));
        let carousel = $(carouselEl).owlCarousel(options);
        setTimeout(()=>{carousel.trigger('refresh.owl.carousel');if(options['smartSpeed']){carousel.trigger('play.owl.autoplay');}});
    }
}
document.querySelectorAll('.owl-carousel').forEach(initalizeOwlCarousel);


// Owl Carousel Nav Buttons
function owlNavigator(btn, type){
    let slider = btn.getAttribute(type == "next" ? "data-owl-next" : "data-owl-prev");
    if (slider){
        $(btn).on("click", (event)=>{if(event.currentTarget.classList.contains('disabled')){return};$(slider).trigger(type == "next" ? "next.owl.carousel" : "prev.owl.carousel");})
    }
}
document.querySelectorAll("[data-owl-next]").forEach((nextBtn)=>{owlNavigator(nextBtn, "next")})
document.querySelectorAll("[data-owl-prev]").forEach((prevBtn)=>{owlNavigator(prevBtn, "prev")})


// Brands Scroller
const hexToRGB = (hex)=>{
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}
const brands = document.querySelector(".home-brands");
if (brands){
const brandsScroller = document.querySelector('.home-brands');
let brandsScrollerActive = 1;
let brandsItems = $('.brand-item');
let brandItemHeight = document.querySelector(".brand-item").getBoundingClientRect().height;
let brandItemGap = 30;
let brandsScrollerEnd = brandItemHeight * brandsItems.length + (brandItemGap * (brandsItems.length - 1));
let brandsProgress = document.querySelector(".brands-progress")
var mainTimeline = new TimelineMax();
let scrolling = document.querySelector(".brands-content .scrolling");
brandsItems.each((index, item)=>{
    gsap.set(item, {y: (brandItemHeight + brandItemGap) * index + (brandItemGap * (index))});
});
gsap.set(scrolling, {yPercent: 0})
let tl = gsap.timeline({
    scrollTrigger: {
        pin: true,
        trigger: brandsScroller,
        start: brandsScrollerStart,
        end: "+="+brandsScrollerEnd,
        scrub: 1,
        onUpdate: (self)=>{
            let brandsScrollerProgress = ((brandsItems.length - 1) * self.progress);
            let prog = brandsScrollerProgress - parseInt(brandsScrollerProgress);
            let progressPercent = self.progress * 100;
            let brandsScrollerActive = parseInt(brandsScrollerProgress);
            $(brandsProgress).css("background", "linear-gradient(to bottom, "+brandsProgress.getAttribute('data-foreground')+" "+progressPercent+"%, "+brandsProgress.getAttribute('data-background')+" "+progressPercent+"%, "+brandsProgress.getAttribute('data-background')+")")
            brandsItems.each((index, item)=>{
                if (index <= brandsScrollerActive){
                    if (index < brandsScrollerActive){    
                        gsap.to(item, {duration: .1, y: (-brandItemHeight * .1) * ((brandsScrollerActive - index) + prog) + (- brandItemGap * ((brandsScrollerActive - index - 1) + prog))});
                    }else if (index == brandsScrollerActive){
                        let color = item.getAttribute('data-color');
                        $(brands).get(0).style.setProperty("--brand-color", color)
                    }
                    gsap.to(item, {duration: .1,
                        scale: (1 - (.1 * (brandsScrollerActive - index + prog))),
                        y: (-brandItemHeight * .1) * ((brandsScrollerActive - index) + prog)
                    })
                }else{
                    gsap.to(item, {duration: .1, y: (brandItemHeight + brandItemGap) * (index - (brandsScrollerProgress)) + (brandItemGap * (index))});
                }
            });
        }
    }
});
}


// Home Slider
const homeSlider = document.querySelector(".home-slider");
const homeSliderContent = document.querySelector(".home-slider-content");
if(homeSlider){

ScrollTrigger.create({
    trigger: homeSlider,
    start: "-110 top",
    scrub: 1,
    onUpdate: (self)=>{
        gsap.set(homeSliderContent, {duration: .1, marginTop: Math.min(self.progress * (self.end - self.start), homeSliderContent.parentElement.parentElement.getBoundingClientRect().height - homeSliderContent.getBoundingClientRect().height - 80)});
    }
});
let slideIndicator = homeSlider.querySelector(".slide-indicator");
let pageIndicator = homeSlider.querySelector(".page-indicator");
let textCarousel = homeSlider.querySelector('.home-slider-text-carousel');
let homeSliderIndex = 0;
let homeSliderIsPlaying=false;
$(".home-slider-navigator button").on('click', (event)=>{
    if(!event.currentTarget.classList.contains('disabled')){
        $(".home-slider-navigator button").each((index, item)=>{
            item.classList.add('disabled');
            setTimeout(()=>{item.classList.remove('disabled')}, 250);
        })
    }
})
$(textCarousel).on('changed.owl.carousel', function(event) {
    gsap.to(slideIndicator, {duration: .25, ease: "Power1.out", opacity: 0, onComplete: ()=>{
        $(slideIndicator).text(textCarousel.querySelector(".owl-stage").children[event.item.index].querySelector(".text-container").getAttribute('data-name'));
        gsap.to(slideIndicator, {duration: .25, ease: "Power1.in", opacity: 1})}})
    gsap.to(pageIndicator, {duration: .25, ease: "Power1.out", opacity: 0, onComplete: ()=>{
        $(pageIndicator).text((event.item.index + 1) + " - " + event.item.count);
        gsap.to(pageIndicator, {duration: .25, ease: "Power1.in", opacity: 1})
    }})
    let isBack = homeSliderIndex > event.item.index;
    let nEl = document.querySelector(".home-slider-images").children[event.item.index];
    let oEl = document.querySelector(".home-slider-images").children[homeSliderIndex];
    gsap.set(nEl, {zIndex: 2, width: "0%", marginLeft: isBack ? "100%" : 0});
    gsap.to(nEl, {width: "100%", marginLeft: 0, onComplete: ()=>{
        gsap.set(nEl, {zIndex: 0});
        oEl.classList.remove('active');
        nEl.classList.add('active');
    }});
    homeSliderIndex = event.item.index;
});
}

$(".input-parent").each((index, inputParent)=>{
    inputParent.addEventListener('focus', (e)=>{
        inputParent.querySelector('.input').focus()
    })
});


// Select Menu
function initalizeSelectInput(triggerEl, menuSelector = ".select-menu"){

    $(triggerEl).on("click", (event)=>{
        if (event.currentTarget.classList.contains("active")){
            return;
        }
        let el = event.currentTarget.querySelector(menuSelector);
        gsap.set(el, {opacity: 1, y: 200})
        gsap.to(el, {y: 0, duration: .5, ease: "elastic.out(1, 1)",})
    });
}
$(".input-select").each((index, item)=>{initalizeSelectInput(item)})
$(".dropdown-trigger").each((index, item)=>{initalizeSelectInput(item, ".dropdown-menu")})


// Language Selector
$(".language-selector-button").on("click", (event)=>{
    let wrapper = event.currentTarget.parentElement.parentElement;
    if (event.currentTarget.classList.contains("active")){
        gsap.to(wrapper, {duration: 0.25, width: 65})
    }
    else{
        gsap.set(wrapper, {width: "auto"})
        gsap.from(wrapper, {duration: 0.25, width: 65})
    }
});


// Header Router
let headerRouterMenuWrapper = document.querySelector(".header-router-menu-wrapper");
let headerRouterMenu = document.querySelector(".header-router-menu");

function setHeaaderRouterMenuHeight(el=headerRouterMenu){
    $(".header-router-menu-wrapper").css("height", el.getBoundingClientRect().height)
}
$(".header-router-menu").on("click", (event)=>{event.stopPropagation();})
document.querySelectorAll(".header-router-item.has-content").forEach((routerItem)=>{
    routerItem.addEventListener("click", (event)=>{
        event.stopPropagation();
        event.currentTarget.classList.add('active');
        setHeaaderRouterMenuHeight(routerItem.querySelector(".content"));
    })
})
document.querySelectorAll(".header-router-item .content-back").forEach((backButton)=>{
    backButton.addEventListener("click", (event)=>{
        event.stopPropagation();
        event.currentTarget.parentElement.parentElement.classList.remove('active');
        setHeaaderRouterMenuHeight();
    })
})
$(".header-router-button").on("click", (event)=>{
    if (event.currentTarget.classList.contains("active")){
        $(event.currentTarget).find(".header-router-item.active").removeClass("active");
        setHeaaderRouterMenuHeight();
        return;
    }
    gsap.set(headerRouterMenuWrapper, {opacity: 1, y: 200})
    gsap.to(headerRouterMenuWrapper, {y: 0, duration: .5, ease: "elastic.out(1, 1)",})
})
setHeaaderRouterMenuHeight()


/* Filter Popup */
document.querySelectorAll(".filter-popup-button").forEach((filterButton)=>{
    filterButton.addEventListener("click", (event)=>{
        let popupWrapper = document.createElement("div");
        popupWrapper.setAttribute("class", "popup-wrapper")
        popupWrapper.innerHTML = `
        <div class="popup filter-popup">
            <div class="popup-top">
                <div class="logo-container">
                    <span class="popup-window-title">Filtreler</span>
                </div>
                <div class="popup-close border-button">
                    <div class="icon cross-icon"></div>
                    Kapat
                </div>
            </div>
            <div class="popup-content">
                <div class="filter-select-container">
                    <span>Haber Bölümü</span>
                    <div class="filter-select activate focusout_inactivate input-select input-arrow arrow-down arrow-dark" tabindex="0">
                        <div class="selected input">Herhangi bir sınıflandırma</div>
                        <ul class="select-menu">
                            <li><a class="activate hvr">Lorem ipsum</a></li>
                            <li><a class="activate hvr">Lorem ipsum</a></li>
                            <li><a class="activate hvr">Lorem ipsum</a></li>
                        </ul>
                    </div>
                </div>
                <div class="filter-select-container">
                    <span>Haber Bölümü</span>
                    <div class="filter-select activate focusout_inactivate input-select input-arrow arrow-down arrow-dark" tabindex="0">
                        <div class="selected input">Herhangi bir konum</div>
                        <ul class="select-menu">
                            <li><a class="activate hvr">Lorem ipsum</a></li>
                            <li><a class="activate hvr">Lorem ipsum</a></li>
                            <li><a class="activate hvr">Lorem ipsum</a></li>
                        </ul>
                    </div>
                </div>
                <div class="button-container flex">
                    <a class="standart-button big-button border-button arrow-anim arrow-dark">Sıfırla</a>
                    <a class="standart-button big-button black-button arrow-anim">Uygula</a>
                </div>
            </div>
        </div>
        `;
        initalizePopup(popupWrapper);
        document.body.appendChild(popupWrapper);
    })
})


function initalizeActivate(el){
    $(el).on("click", (event)=>{
        event.stopPropagation();
        if(!el.classList.contains("no_propagation") || event.target==el){
            event.currentTarget.classList.toggle("active");
        }
    })   
}
function initalizeFocusoutInactive(el){
    $(el).on("focusout", (event)=>{
        event.currentTarget.classList.remove("active")
    })  
}
$(".activate").each((_, item)=>{initalizeActivate(item)});
$(".focusout_inactivate").each((_, item)=>{initalizeFocusoutInactive(item)});
document.addEventListener('DOMContentLoaded', ()=>{
    $('.loader').css('display', 'none')
})