import ATab from '/js/libs/js-ATab.js';
function isInViewport(element) {
    const rect = element.getBoundingClientRect();
    return (
        rect.top < window.innerHeight &&
        rect.bottom > 0 &&
        rect.left < window.innerWidth &&
        rect.right > 0
    );
}
function updateActiveSlideShow(swiperInstance) {
    swiperInstance.slides.forEach(slide => slide.classList.remove('show'));

    const activeSlide = swiperInstance.slides[swiperInstance.activeIndex];
    if (isInViewport(activeSlide)) {
        activeSlide.classList.add('show');
    }
}

window.L1000 = function () {
    const swiper = new Swiper('.mainSlider', {
        loop: true,
        effect: 'creative',
        creativeEffect: {
            limitProgress: 1,
            prev: { translate: ['-40%', 0, -1], opacity: 0, shadow: true },
            next: { translate: ['40%', 0, -1], opacity: 0, shadow: true }
        },
        autoplay: {
            delay: 5000,      // 5s
            disableOnInteraction: false, // không dừng khi hover hay click
        },
        loop: true,  // bật loop để chạy liên tục
        allowTouchMove: true,
        simulateTouch: true,
        followFinger: true,
        threshold: 0,
        speed: 1000,
        navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
        },
        on: {
            init: function () {
                updateActiveSlideShow(this);
            },
            slideChangeTransitionEnd: function () {
                updateActiveSlideShow(this);
            }
        }
    });
    document.addEventListener('visibilitychange', function () {
        if (document.visibilityState === 'hidden') {
            // Remove class show khỏi tất cả các slide
            swiper.slides.forEach(slide => slide.classList.remove('show'));
        }

        if (document.visibilityState === 'visible') {
            // Add class show lại cho slide đang active
            const activeSlide = swiper.slides[swiper.activeIndex];
            if (activeSlide) {
                // Delay một chút để CSS animation có thời gian reset
                window.requestTimeout(() => {
                    activeSlide.classList.add('show');
                }, 50); // delay nhẹ để đảm bảo browser detect lại class
            }
        }
    });
    var tabs = new ATab(document.querySelector(".tabQuoute .atabs"), document.querySelector(".tabQuoute .tabcontents"));

    const parallaxEls = document.querySelectorAll('.parallax');
    let ticking = false;
    const swiper1 = new Swiper('.airlineSwiper', {
        slidesPerView: 1,
        spaceBetween: 30,
        autoplay: {
            delay: 2000,      // 5s
            disableOnInteraction: false, // không dừng khi hover hay click
        },
        loop: true,  // bật loop để chạy liên tục
        speed: 1000,
        navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
        },
        loopedSlides: 5,  // số slide duplicate
        breakpoints: {
            1200: { slidesPerView: 4 },  // màn hình ≥1200px
            768: { slidesPerView: 3 },  // ≥768px=
            0: { slidesPerView: 2 }   // <576px
        },
    });
    parallaxEls.forEach(el => {
        const parent = el.closest(".con-parallax");
        if (parent) {
            parent.style.height = parent.querySelector("[data-content]").offsetHeight + "px";
        }
    });
    window.app.on("App_Scrolling", (t) => {
        if (!ticking) {
            window.requestAnimationFrame(() => {
                updateParallax(t, parallaxEls);
                ticking = false;
            });
            ticking = true;
        }
    });
    const countNum = document.querySelectorAll('[CountNumber]');
    let tickingC = false;
    window.app.on("App_Scrolling", (t) => {
        if (!tickingC) {
            window.requestAnimationFrame(() => {
                countNum.forEach((el) => {
                    animateCount(el);
                })
                tickingC = false;
            });
            tickingC = true;
        }
    });
    const swiper2 = new Swiper('.ourBlogSwiper', {
        slidesPerView: 1,
        spaceBetween: 0,
        autoplay: {
            delay: 2000,      // 5s
            disableOnInteraction: true,
        },
        loop: true,  // bật loop để chạy liên tục
        speed: 1000,
        navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
        },
        loopedSlides: 5,  // số slide duplicate
        breakpoints: {
            1400: { slidesPerView: 4 },
            992: { slidesPerView: 3 },  // màn hình ≥1200px
            576: { slidesPerView: 2 },  // ≥768px=
            0: { slidesPerView: 1 }   // <576px
        },
    });

      

    const swiper3 = new Swiper(".custSwiper", {
        slidesPerView: 1,
        spaceBetween: 0,
        autoplay: {
            delay: 2000,      // 5s
            disableOnInteraction: true,
        },
        loop: true,  // bật loop để chạy liên tục
        speed: 1000,
        navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
        },
        loopedSlides: 5,  // số slide duplicate
        breakpoints: {
            992: { slidesPerView: 3 },  // màn hình ≥1200px
            576: { slidesPerView: 2 },  // ≥768px=
            0: { slidesPerView: 1 }   // <576px
        }
    });

    const swiper4 = new Swiper(".swiperAward", {
        slidesPerView: 1,
        spaceBetween: 0,
        autoplay: {
            delay: 2000,      // 5s
            disableOnInteraction: true,
        },
        loop: true,  // bật loop để chạy liên tục
        speed: 1000,
        navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
        },
        loopedSlides: 5,  // số slide duplicate
        breakpoints: {
            992: { slidesPerView: 1 },  // màn hình ≥1200px
            0: { slidesPerView: 2 }   // <576px
        }
    });
}
function animateCount(el) {
    const rect = el.getBoundingClientRect();
    const inView = rect.bottom > 0 && rect.top < window.innerHeight;
    if (el.hasAttribute("render")) {
        if (!inView) {
            el.removeAttribute("render");
        }
        return;
    }
    if (inView) {
        el.setAttribute("render", "");
        const min = parseInt(el.getAttribute("num-min") ?? 0);
        const max = parseInt(el.getAttribute("num-max") ?? 1);
        const prefix = el.getAttribute("prefix") ?? "";
        const duration = parseInt(el.getAttribute("duration") ?? 1000); // ms
        const interval = 10; // ms mỗi tick

        const steps = duration / interval;
        const stepValue = Math.ceil((max - min) / steps);

        let current = min;
        let tickCount = 0;

        function tick() {
            current = Math.min(min + stepValue * tickCount, max);
            el.textContent = prefix + current.toLocaleString("en-US");
            tickCount++;

            if (tickCount <= steps) {
                window.requestTimeout(tick, interval);
            }
        }

        tick(); // khởi chạy
    } 
}
function updateParallax(t, parallaxEls) {
    parallaxEls.forEach(el => {
        const section = el.closest('.con-parallax');
        if (!section) return;

        const rect = section.getBoundingClientRect();
        const sectionHeight = section.offsetHeight;

        // Chỉ xử lý khi section trong khung nhìn
        const inView = rect.bottom > 0 && rect.top < window.innerHeight;
        if (!inView) return;

        // Set height parent 1 lần
        const content = section.querySelector('[data-content]');
        if (content && !section.dataset.heightSet) {
            section.style.height = content.offsetHeight + 'px';
            section.dataset.heightSet = 'true'; // đánh dấu đã set height
        }

        const img = el.querySelector('.bg-img');
        if (!img) return;

        const imgHeight = img.offsetHeight;
        const depth = parseFloat(el.dataset.depth ?? 1); // 1 = chạy hết, <1 = chạy ít hơn

        // progress: 0 khi section top chạm viewport top, 1 khi section bottom chạm viewport bottom
        const progress = (window.innerHeight - rect.top) / (window.innerHeight + sectionHeight);
        const clamped = Math.min(1, Math.max(0, progress));

        // scrollable = toàn bộ quãng đường ảnh có thể chạy
        const scrollable = imgHeight - sectionHeight;

        // offset Y
        const offsetY = -clamped * scrollable * depth;
        img.style.transform = `translate(-50%, ${offsetY}px)`;
    });
}

window.AScript.set("1000", true);