<script setup lang="ts">
// import

import { Swiper, SwiperSlide } from "swiper/vue";
import type { SwiperClass } from "swiper/react";
import useHomeData from "~/composables/api/home/useHomeData";

// state

const { data: homeData } = useHomeData();
const { $gsap: gsap, $ScrollTrigger: ScrollTrigger } = useNuxtApp();
const swiper_instance = ref<SwiperClass | null>(null);

const observerTarget = ref(null);
const shouldPauseVideos = ref(false);

useIntersectionObserver(observerTarget, ([entry], observerElement) => {
    shouldPauseVideos.value = entry.rootBounds ? !entry.isIntersecting : false;
});

const isMuted = ref(true);
const slidesPerView = ref(1);

let gsapTimeline: gsap.core.Timeline;
let scrollTrigger: ScrollTrigger;

// methods

const onSwiper = (swiper: SwiperClass) => {
    swiper_instance.value = swiper;
};

const updateVideoStates = () => {
    const activeIndex = swiper_instance.value?.realIndex || 0;
    const videosElements = document.querySelectorAll(`.slide-video`) as NodeListOf<HTMLVideoElement>;
    videosElements.forEach((videoElement) => {
        if (videoElement.id === `slide-video-${activeIndex}` && !shouldPauseVideos.value) {
            videoElement.play();
        } else {
            videoElement.pause();
        }
    });
};

// watch

watch(
    () => [shouldPauseVideos.value, swiper_instance.value?.realIndex],
    () => {
        updateVideoStates();
    },
);

// lifecycle

const initializeGsapAnimation = () => {
    gsapTimeline
        .fromTo(
            ".header-slider-item",
            {
                borderRadius: 0,
                height: "100svh",
            },
            {
                height: "80svh",
                borderRadius: "20px",
            },
        )
        .fromTo(
            slidesPerView,
            {
                value: 1,
            },
            {
                value: 1.2,
            },
            "=",
        )
        .fromTo(
            ".header-navbar-item",
            {
                filter: "invert(100%)",
            },
            {
                filter: "invert(0%)",
            },
            "=",
        )
        .fromTo(
            "#header-navbar",
            {
                boxShadow: "0 10px 15px -3px rgba(0,0,0,0)",
                background: "transparent",
            },
            {
                boxShadow: "0 10px 15px -3px rgba(0,0,0,0.05)",
                background: "white",
            },
        )
        .fromTo(
            "#header-slider-wrapper",
            {
                marginTop: "0px",
                scale: 1.025,
            },
            {
                marginTop: () => {
                    const navbarEl = document.querySelector("#header-navbar") as HTMLDivElement;
                    return `${navbarEl.clientHeight}px`;
                },
                scale: 1,
            },
            "=",
        );
};

const resetTimelineForMobile = () => {
    gsap.to("#header-navbar", {
        background: "white",
        boxShadow: "0 10px 15px -3px rgba(0,0,0,0.05)"
    });
    gsap.to(".header-navbar-item", {
        filter: "invert(0%)",
    });
    gsap.set(".header-slider-item", {
        borderRadius: "20px",
        height: "450px",
    });
};

onMounted(() => {
    updateVideoStates();

    gsapTimeline = gsap.timeline();

    initializeGsapAnimation();

    scrollTrigger = ScrollTrigger.create({
        anticipatePin: 1,
        trigger: "#header-slider-container",
        animation: gsapTimeline,
        scrub: 1,
        pin: true,
        start: "top top",
        // markers: true,
        end: "bottom top",
    });

    const calculateOnResize = () => {
        if (window.innerWidth > 768) {
            scrollTrigger.enable();
        } else {
            resetTimelineForMobile();
            scrollTrigger.disable();
        }
    };

    setTimeout(() => {
        calculateOnResize();
    }, 100);

    setTimeout(() => {
        calculateOnResize();
    }, 200);

    window.addEventListener("resize", () => {
        calculateOnResize();
    });
});

onUnmounted(() => {
    resetTimelineForMobile();
    scrollTrigger.disable();
});
</script>

<template>
    <div
        id="header-slider-container"
        class="w-full z-50"
    >
        <div
            id="header-slider-wrapper"
            class="relative"
            :class="swiper_instance ? '' : 'bg-black min-h-svh'"
        >
            <Swiper
                ref="observerTarget"
                :class="swiper_instance ? '' : 'opacity-0'"
                :slides-per-view="slidesPerView"
                :loop="true"
                :centered-slides="true"
                :breakpoints="{
                    768: {
                        spaceBetween: 40,
                    },
                }"
                @swiper="onSwiper"
            >
                <SwiperSlide
                    v-for="(slide, index) in homeData!.sliders"
                    :key="slide.id"
                >
                    <div class="max-md:container">
                        <div class="header-slider-item relative w-full overflow-hidden max-md:rounded-[20px]">
                            <template v-if="!!slide.video">
                                <video
                                    :id="`slide-video-${index}`"
                                    :muted="swiper_instance?.realIndex !== index ? true : isMuted"
                                    loop
                                    playsinline
                                    webkit-playsinline
                                    class="slide-video absolute inset-0 size-full object-cover brightness-90"
                                    :src="slide.video"
                                    poster="/img/test-thumbnail.jpeg"
                                />
                            </template>

                            <NuxtImg
                                v-else
                                preload
                                loading="eager"
                                fetch-priority="high"
                                class="absolute inset-0 size-full object-cover"
                                :src="slide.image!"
                                :alt="slide.title"
                            />

                            <div class="size-full absolute z-10 bg-linear-to-t from-black/50 to-transparent" />

                            <div
                                :class="swiper_instance?.realIndex !== index ? 'opacity-0' : ''"
                                class="w-full transition-opacity pb-6 xs:pb-10 lg:pb-16 px-6 xs:px-10 lg:px-16 gap-6 xs:gap-10 lg:gap-12 container flex flex-col h-full justify-end relative z-10"
                            >
                                <div class="header-slider-item-child w-full">
                                    <div class="border-b border-white/10 pb-6 flex flex-col gap-2 md:gap-4">
                                        <div class="flex items-center gap-4 lg:gap-8">
                                            <div
                                                class="hover:scale-110 size-[36px] md:size-[42px] lg:size-[50px] relative flex items-center justify-center"
                                            >
                                                <div
                                                    class="size-full scale-75 bg-white absolute rounded-full animate-ping"
                                                />
                                                <button
                                                    @click="isMuted = !isMuted"
                                                    class="transition-all cursor-pointer flex-center bg-white z-10 size-full rounded-full"
                                                >
                                                    <Icon
                                                        :name="
                                                            isMuted ? 'ci:bi-volume-mute-fill' : 'ci:bi-volume-up-fill'
                                                        "
                                                        class="text-black size-4 md:size-[18px] lg:size-[24px]"
                                                    />
                                                </button>
                                            </div>
                                            <NuxtLink
                                                :to="slide.link"
                                                class="typo-h-6 md:typo-h-4 lg:typo-h-1 tracking-[-2px] text-white"
                                            >
                                                {{ slide.title }}
                                            </NuxtLink>
                                        </div>
                                        <div class="flex justify-between items-center">
                                            <span class="truncate typo-p-xs md:typo-p-sm lg:typo-p-lg text-white">
                                                {{ slide.description }}
                                            </span>
                                            <NuxtLink
                                                :to="slide.link"
                                                class="relative max-sm:hidden"
                                            >
                                                <!-- <NuxtImg
                                                    class="aspect-square w-[110px] lg:w-[120px] translate-y-[-75px] lg:translate-y-[-82px] absolute left-1/2 -translate-x-1/2 z-10"
                                                    :style="{
                                                        filter: 'drop-shadow(0px 0px 20px rgba(0, 0, 0, 0.4))',
                                                    }"
                                                    src="/img/heymlz/heymlz-seat.gif"
                                                    loading="lazy"
                                                    fetch-priority="low"
                                                /> -->

                                                <Button
                                                    variant="primary"
                                                    class="max-lg:typo-label-xs px-12 rounded-full hover:bg-blue-500 hover:text-white"
                                                >
                                                    مشاهده
                                                </Button>
                                            </NuxtLink>
                                        </div>
                                    </div>
                                </div>

                                <div
                                    id="header-slider-pagination-child"
                                    class="flex items-center justify-between"
                                >
                                    <button
                                        @click="swiper_instance?.slidePrev()"
                                        class="relative"
                                    >
                                        <div
                                            class="size-8 blur-xl bg-white absolute ping-animation max-sm:hidden"
                                        ></div>
                                        <Icon
                                            class="**:stroke-white cursor-pointer size-6 md:size-8"
                                            name="ci:arrow-right"
                                        />
                                    </button>
                                    <div class="flex items-center justify-center gap-3 text-white">
                                        <div
                                            v-for="(_slide, index) in homeData!.sliders"
                                            :class="
                                                swiper_instance?.realIndex === index ? 'bg-white' : 'bg-transparent'
                                            "
                                            class="border border-white size-2 md:size-3 rounded-full transition-all duration-200"
                                        ></div>
                                    </div>
                                    <button
                                        @click="swiper_instance?.slideNext()"
                                        class="relative"
                                    >
                                        <div
                                            class="size-8 blur-xl bg-white absolute ping-animation max-sm:hidden"
                                        ></div>
                                        <Icon
                                            class="**:stroke-white cursor-pointer size-6 md:size-8"
                                            name="ci:arrow-left"
                                        />
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </SwiperSlide>
            </Swiper>
        </div>
    </div>
</template>

<style>
@keyframes ping-anime {
    0% {
        scale: 0.7;
        opacity: 1;
    }

    10% {
        scale: 2;
        opacity: 0;
    }

    100% {
        scale: 2;
        opacity: 0;
    }
}

.ping-animation {
    animation-name: ping-anime;
    animation-iteration-count: infinite;
    animation-duration: 6s;
}
</style>
