<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 showLoadingOverlay = useState("showLoadingOverlay");

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) => {
    setTimeout(() => {
        showLoadingOverlay.value = false;
    }, 1000);
    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", {
            background: "transparent"
        }, {
            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"
    });
    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">
            <Swiper
                ref="observerTarget"
                :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"
                                />
                            </template>

                            <NuxtImg
                                v-else
                                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 ? 'bi:volume-mute-fill' : 'bi:volume-up-fill'"
                                                        class="text-black size-4 md:size-[18px] lg:size-[24px]"
                                                    />
                                                </button>
                                            </div>
                                            <h3 class="typo-h-6 md:typo-h-4 lg:typo-h-1 tracking-[-2px] text-white">
                                                {{ slide.title }}
                                            </h3>
                                        </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">
                                                <Button
                                                    class="max-sm:hidden max-lg:typo-label-xs invert rounded-full hover:bg-transparent"
                                                >
                                                    مشاهده
                                                </Button>
                                            </NuxtLink>
                                        </div>
                                    </div>
                                </div>

                                <div
                                    id="header-slider-pagination-child"
                                    class="flex items-center justify-between"
                                >
                                    <button @click="swiper_instance?.slidePrev()">
                                        <Icon
                                            class="**:stroke-white cursor-pointer size-5 md:size-6"
                                            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>
                                        <Icon
                                            @click="swiper_instance?.slideNext()"
                                            class="**:stroke-white cursor-pointer size-5 md:size-6"
                                            name="ci:arrow-left"
                                        />
                                    </button>
                                </div>

                            </div>

                        </div>
                    </div>
                </SwiperSlide>
            </Swiper>
        </div>

    </div>
</template>