"use strict";
// sticky step section
gsap.registerPlugin(ScrollTrigger);

const parallax_box = document.querySelectorAll("[data-parallax]");
parallax_box.forEach(function (prel) {
    const parallax_el = prel.querySelectorAll("[data-speed]");
    parallax_el.forEach(function (el) {
        let smoothVal = Number(el.dataset.speed === 0 ? 1 : el.dataset.speed) * 100;
        gsap.to(el, {
            yPercent: -smoothVal,
            ease: "none",
            scrollTrigger: {
                trigger: prel,
                scrub: 1.1
            },
        });
    })
})

jQuery(document).ready(function ($) {
    // document start


    // Navbar
    $("<span class='clickD'></span>").insertAfter(".navbar-nav li.menu-item-has-children > a");
    $('.navbar-nav li .clickD').click(function (e) {
        e.preventDefault();
        var $this = $(this);
        if ($this.next().hasClass('show')) {
            $this.next().removeClass('show');
            $this.removeClass('toggled');
        }
        else {
            $this.parent().parent().find('.sub-menu').removeClass('show');
            $this.parent().parent().find('.toggled').removeClass('toggled');
            $this.next().toggleClass('show');
            $this.toggleClass('toggled');
        }
    });

    $(window).on('resize', function () {
        if ($(this).width() < 1025) {
            $('html').click(function () {
                $('.navbar-nav li .clickD').removeClass('toggled');
                $('.toggled').removeClass('toggled');
                $('.sub-menu').removeClass('show');
            });
            $(document).click(function () {
                $('.navbar-nav li .clickD').removeClass('toggled');
                $('.toggled').removeClass('toggled');
                $('.sub-menu').removeClass('show');
            });
            $('.navbar-nav').click(function (e) {
                e.stopPropagation();
            });
        }
    });
    // Navbar end



    /* ===== For menu animation === */
    $(".navbar-toggler").click(function () {
        $(".navbar-toggler").toggleClass("open");
        $(".navbar-toggler .stick").toggleClass("open");
        $('body,html').toggleClass("open-nav");
    });

    // Navbar end


    // Sticky Nav
    $(window).scroll(function () {
        var scroll = $(window).scrollTop();
        if (scroll > 0) {
            $(".main-head").addClass("fixed");
        }
        else {
            $(".main-head").removeClass("fixed");
        }
    })

    // back to top
    if ($("#scroll").length) {
        $(window).scroll(function () {
            if ($(this).scrollTop() > 200) {
                $('#scroll').fadeIn(200);
            } else {
                $('#scroll').fadeOut(200);
            }
        });
        $('#scroll').click(function () {
            $("html, body").animate({ scrollTop: 0 }, 500);
            return false;
        });
    }

    $(".top_btn").each(function () {
        $(this).on("click", function (e) {
            e.preventDefault();

            var target = $($(this).attr("href"));
            if (!target.length) return;

            $("html, body").animate({
                scrollTop: target.offset().top - $(".main-head").outerHeight()
            }, 500);
        });
    });




    // Faq
    if ($('.accr-container').length) {
        $(this).find('.accr-item:nth-child(1)').addClass('open');
        $(this).find('.accr-item:nth-child(1) .accr-hd').next().slideDown();
    }

    $(".accr-hd").on('click', function () {
        $(this).parent().toggleClass('open');
        $(this).next().stop(true, true).slideToggle();
        $(".accr-hd").not(this).parent().removeClass('open');
        $(".accr-hd").not(this).next().slideUp();
    })

    $('.navbar-nav a[href*="#"]').click(function () {
        $(".navbar-collapse").removeClass("show");
        $(".navbar-toggler").removeClass("open");
        $(".navbar-toggler .stick").removeClass("open");
        $('body,html').removeClass("open-nav");
    });

    $(document).ready(function () {
        function initMenuScroll() {
            var headerHeight = $('.main-head').outerHeight() || 0;
            $('.main-head .navbar-nav').menuScroll(headerHeight);
        }

        initMenuScroll();
    });

    jQuery.fn.extend({
        menuScroll: function (offset) {
            var topMenu = this;
            var topOffset = offset ? offset : 0;
            var menuItems = $(topMenu).find('a[href^="#"]');
            var lastId;

            var scrollItems = $(menuItems).map(function () {
                var target = $($(this).attr("href"));
                if (target.length) {
                    return target;
                }
            });

            $(topMenu).off("click.menuScroll").on("click.menuScroll", 'a[href^="#"]', function (e) {
                var href = $(this).attr("href");
                var target = $(href);

                if (!target.length) return;

                var offsetTop = href === "#" ? 0 : target.offset().top - topOffset;

                $('html, body').stop().animate({
                    scrollTop: offsetTop
                }, 300);

                e.preventDefault();
            });

            $(window).off("scroll.menuScroll").on("scroll.menuScroll", function () {
                var fromTop = $(window).scrollTop() + topOffset + 10;

                var current = $(scrollItems).map(function () {
                    if ($(this).offset().top <= fromTop && $(this).offset().top + $(this).outerHeight() > fromTop) {
                        return this;
                    }
                });

                current = current[current.length - 1];
                var id = current && current.length ? current[0].id : "";

                if (lastId !== id) {
                    lastId = id;

                    $(menuItems)
                        .parent().removeClass("current-menu-item")
                        .end()
                        .filter("[href='#" + id + "']")
                        .parent()
                        .addClass("current-menu-item");
                }
            });

            return this;
        }
    });

    $(document).ready(function () {
        $('.main-head .navbar-nav').menuScroll($('.main-head').outerHeight());
    });

    // splitting text
    Splitting({
        target: "[data-splitting]",
        by: "chars",
    });
    // splitting text end

    // reveal animation
    if ($(".reveal").length) {
        var reveal = gsap.utils.toArray(".reveal > *");

        reveal.forEach((elem, i) => {
            ScrollTrigger.create({
                trigger: elem,
                start: "top 90%",
                end: "top 15%",
                //toggleActions: "play reverse",
                onEnter() {
                    elem.classList.add('play-reveal');
                },
                // onLeave() {
                //   elem.classList.remove('play-reveal');
                // },
                // onEnterBack() {
                //   elem.classList.add('play-reveal');
                // },
                // onLeaveBack() {
                //   elem.classList.remove('play-reveal');
                // }
            });


        })
    }
    // reveal animation end


    // equal height 
    function equal_height() {
        $('.membership-card-inner .tagline').matchHeight({ property: 'min-height' });
    }
    equal_height();
    $(window).on('load', function (event) {
        equal_height();
    });
    $(window).resize(function (event) {
        equal_height();
    });




    if ($(".feature-sec").length) {
        var featureRevel = document.querySelector(".feature-sec");
        let Tl = gsap.timeline({
            scrollTrigger: {
                trigger: ".feature-sec",
                start: "top 20%",
                end: "bottom 50%",
                scrub: 1,
                onEnter() {
                    $(".feature-sec").addClass('play-reveal');
                }
            }
        })
    }

    setTimeout(() => {
        if ($('[data-anim="parent-anim-sec"]').length) {
            const parentAnimation = document.querySelectorAll('[data-anim="parent-anim-sec"]');
            parentAnimation.forEach((elem, index) => {
                let moveUpElem = elem.querySelectorAll("[data-move]");
                let slideElem = elem.querySelectorAll("[data-slide]");
                let moveTl = gsap.timeline();
                let slideTl = gsap.timeline();
                moveUpElem.forEach(function (elem2, index2) {
                    if (elem2.dataset.move == "up") {
                        gsap.set(elem2, { y: 60, opacity: 0 });
                        moveTl.to(elem2, {
                            ease: "none",
                            duration: 0.6,
                            y: 0,
                            opacity: 1,
                        })
                    }

                    if (elem2.dataset.move == "scale-up") {
                        gsap.set(elem2, { y: 50, scale: 0 });
                        slideTl.to(elem2, {
                            ease: "Power3.easeOut",
                            duration: 0.8,
                            scale: 1,
                            opacity: 1,
                            delay: () => {
                                if (elem2.dataset.delay) {
                                    return elem2.dataset.delay;
                                } else {
                                    return 0;
                                }
                            },
                            y: 0,
                        }, "=-0.2")
                    }
                    if (elem2.dataset.move == "pop-up") {
                        gsap.set(elem2, { opacity: 0, scale: 0.7, y: 40, });
                        slideTl.to(elem2, {
                            ease: "bounce",
                            duration: 2,
                            scale: 1,
                            opacity: 1,
                            y: 0,
                            delay: () => {
                                if (elem2.dataset.delay) {
                                    return elem2.dataset.delay;
                                } else {
                                    return 0;
                                }
                            },
                        }, "=-0.2")
                    }
                    moveTl.pause();
                    ScrollTrigger.create({
                        trigger: elem2,
                        start: "top 95%",
                        animation: moveTl,
                        //markers:true,
                    })
                });

                slideElem.forEach(function (elem2, index2) {
                    if (elem2.dataset.slide == "right") {
                        gsap.set(elem2, { x: -200, opacity: 0, });
                        slideTl.to(elem2, {
                            //   stagger: 0.2,
                            ease: "Power3.easeOut",
                            duration: 1.2,
                            opacity: 1,
                            x: 0,
                        }, (index2 == 0 ? "" : "-=0.7"))
                    }
                    if (elem2.dataset.slide == "left") {
                        gsap.set(elem2, { x: 100, opacity: 0, });
                        slideTl.to(elem2, {
                            //   stagger: 0.2,
                            ease: "Power3.easeOut",
                            duration: 0.8,
                            opacity: 1,
                            x: 0,
                        }, (index2 == 0 ? "" : "-=0.7"))
                    }

                    ScrollTrigger.create({
                        trigger: elem2,
                        start: "top 85%",
                        animation: slideTl,
                        //markers:true,
                    })
                });

            })
        }
    }, 10);

    if ($(".risk-management-sec").length) {
        let redLine = document.querySelector('.red-bar');
        let redDrawTl = gsap.timeline({});
        gsap.set([redLine], {
            clipPath: "polygon(0% 0%, 0% 0%, 0% 100%, 0% 100%)",
        })

        redDrawTl.to(redLine, {
            clipPath: "polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%)",
            duration: 0.5,
            ease: "none",
            delay: 0.5,
        })
        redDrawTl.pause();
        ScrollTrigger.create({
            trigger: redLine,
            start: "top 80%",
            animation: redDrawTl,
        })
    }

    if ($("[data-parallax]").length) {
        document.querySelectorAll("[data-parallax]").forEach((el) => {
            let pr_val = Number(el.dataset.parallax) * 100;
            gsap.to(el, {
                yPercent: pr_val,
                duration: 1,
                ease: "none",
                scrollTrigger: {
                    trigger: el,
                    start: "top bottom",
                    end: "bottom top",
                    scrub: 1.3,
                    invalidateOnRefresh: true,
                    // markers: true,
                },
            });
        });

    }


    $(".header-search").on('click', function () {
        $(".search-popup-wrap").slideToggle();
        return false;
    });

    $(".search-close").on('click', function () {
        $(".search-popup-wrap").slideUp(500);
    });


    // const swiper = new Swiper(".banner-sec", {
    //     speed: 1000,
    //     parallax: true,
    //     loop: true,
    //     autoplay: {
    //         delay: 5000,
    //         disableOnInteraction: false,
    //     },
    //     pagination: {
    //         el: ".swiper-pagination",
    //         clickable: true,
    //     },
    //     navigation: {
    //         nextEl: ".swiper-button-next",
    //         prevEl: ".swiper-button-prev",
    //     }
    // });



    $(document).ready(function () {
        // Main image slider
        $('.main-slider').slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            arrows: false,
            fade: true,
            asNavFor: '.thumb-slider'
        });

        // Thumbnail navigation slider
        $('.thumb-slider').slick({
            slidesToShow: 4,
            slidesToScroll: 1,
            asNavFor: '.main-slider',
            dots: false,
            focusOnSelect: true,
            autoplay: true,
            autoplaySpeed: 3000,
            speed: 1000,
            infinite: true,
            arrows: false,
            centerMode: false
        });
    });



    const bannerSlider = new Swiper(".banner-swiper", {
        slidesPerView: 1,
        spaceBetween: 0,
        speed: 1500,
        autoplay: {
            delay: 4000,
            disableOnInteraction: false,
        },
        effect: "fade",
        parallax: true,
        loop: true,
        navigation: {
            prevEl: ".mil-banner-prev",
            nextEl: ".mil-banner-next"
        },
        pagination: {
            el: ".swiper-pagination",
            clickable: true,
        },
    });

    // document end

})

const lengthCounter = document.querySelectorAll(".counter").length;
if (lengthCounter) {
    const counterUp = window.counterUp.default
    const callback = entries => {
        entries.forEach(entry => {
            const el = entry.target
            if (entry.isIntersecting && !el.classList.contains('is-visible')) {
                counterUp(el, {
                    duration: 3000,
                    delay: 16,
                })
                el.classList.add('is-visible')
            }
        })
    }

    const IO = new IntersectionObserver(callback, { threshold: 1 })

    const allel = document.querySelectorAll('.counter')
    allel.forEach(function (el) {
        IO.observe(el);
    });
}


// const navbar = document.querySelector('.main-head');
// let navPos = document.querySelector('.main-head').clientHeight;
// let scrollTop = window.scrollY || document.documentElement.scrollTop;
// let lastScrollTop;
// // For Navbar sticky on mouse scroll down and hide on mouse scroll up
// window.addEventListener('scroll', () => {
//     navPos = document.querySelector('.main-head').clientHeight;
//     scrollTop = window.scrollY || document.documentElement.scrollTop;
//     scrollTop > lastScrollTop && scrollTop > navPos ? navbar.style.top = `${-navPos}px` : navbar.style.top = '0';
//     scrollTop > navPos ? navbar.classList.add('fixed') : navbar.classList.remove('fixed');
//     lastScrollTop = scrollTop;
// });
// // For Navbar sticky when we reload a page
// window.addEventListener('load', () => {
//     navPos = document.querySelector('.main-head').clientHeight;
//     scrollTop = window.scrollY || document.documentElement.scrollTop;
//     scrollTop > navPos ? navbar.classList.add('fixed') : navbar.classList.remove('fixed');
// })


const categoriesSwiper = new Swiper('.categories-swiper', {
    slidesPerView: 4,
    spaceBetween: 30,
    loop: true,
    speed: 800,
    autoplay: {
        delay: 3000,
        disableOnInteraction: false,
        pauseOnMouseEnter: true,
    },
    centeredSlides: false,
    pagination: {
        el: '.swiper-pagination',
        clickable: true,
    },
    breakpoints: {
        0: {
            slidesPerView: 1.2,
        },
        576: {
            slidesPerView: 2,
        },
        768: {
            slidesPerView: 3,
        },
        992: {
            slidesPerView: 4,
        }
    }
});

const expertsSwiper = new Swiper('.experts-swiper', {
    slidesPerView: 5,
    spaceBetween: 24,
    loop: true,
    speed: 800,
    centeredSlides: false,
    pagination: {
        el: '.swiper-pagination',
        clickable: true,
    },
    autoplay: {
        delay: 3000,
        disableOnInteraction: false,
        pauseOnMouseEnter: true,
    },

    breakpoints: {
        0: {
            slidesPerView: 1.2,
        },
        576: {
            slidesPerView: 2,
        },
        768: {
            slidesPerView: 3,
        },
        992: {
            slidesPerView: 4,
        },
        1200: {
            slidesPerView: 5,
        }
    }
});

const testimonialSwiper = new Swiper('.testimonials-swiper', {
    slidesPerView: 4,
    spaceBetween: 24,
    loop: true,
    speed: 1500,
    autoplay: {
        delay: 3000,
        disableOnInteraction: false,
        pauseOnMouseEnter: true,
    },
    navigation: {
        nextEl: '.testimonial-next',
        prevEl: '.testimonial-prev',
    },

    breakpoints: {
        0: {
            slidesPerView: 1.1,
        },
        576: {
            slidesPerView: 2,
        },
        768: {
            slidesPerView: 3,
        },
        1200: {
            slidesPerView: 4,
        }
    }
});



const cards = document.querySelectorAll('.link-card');

if (cards.length > 0) {
    cards.forEach(($card) => {
        let bounds;

        function rotateToMouse(e) {
            const mouseX = e.clientX;
            const mouseY = e.clientY;
            const leftX = mouseX - bounds.x;
            const topY = mouseY - bounds.y;
            const center = {
                x: leftX - bounds.width / 2,
                y: topY - bounds.height / 2,
            };
            const distance = Math.sqrt(center.x ** 2 + center.y ** 2);

            // Enhanced rotation depth
            const rotateX = (center.y / bounds.height) * 8; // max 20deg
            const rotateY = -(center.x / bounds.width) * 8;

            $card.style.transform = `
        perspective(800px)
        scale3d(1.01, 1.01, 1.01)
        rotateX(${rotateX}deg)
        rotateY(${rotateY}deg)
      `;

            // Golden reactive glow
            //     const glow = $card.querySelector('.glow');
            //     if (glow) {
            //         glow.style.backgroundImage = `
            //   radial-gradient(
            //     circle at ${leftX}px ${topY}px,
            //     rgba(255, 215, 120, 0.45),
            //     rgba(207, 169, 62, 0.25),
            //     rgba(0, 0, 0, 0.05)
            //   )
            // `;
            //     }
        }

        $card.addEventListener('mouseenter', () => {
            bounds = $card.getBoundingClientRect();
            document.addEventListener('mousemove', rotateToMouse);
        });

        $card.addEventListener('mouseleave', () => {
            document.removeEventListener('mousemove', rotateToMouse);
            $card.style.transition = 'transform 0.6s ease';
            $card.style.transform = 'perspective(800px) rotateX(0) rotateY(0) scale3d(1,1,1)';
            const glow = $card.querySelector('.glow');
            if (glow) glow.style.backgroundImage = '';
            setTimeout(() => {
                $card.style.transition = '';
            }, 600);
        });
    });
}


document.addEventListener("DOMContentLoaded", function () {
    function initCarCards(wrap) {
        const carCards = wrap.querySelectorAll(".car-card");
        const radios = wrap.querySelectorAll(".car-radio-area input[type='radio']");

        if (carCards.length > 0 && radios.length > 0) {
            function showCard(index) {
                carCards.forEach((card, i) => {
                    card.style.display = i === index ? "block" : "none";
                });
            }

            // ✅ Initialize: show first card & check first radio
            showCard(0);
            radios[0].checked = true;

            // Event listener per radio
            radios.forEach((radio, index) => {
                radio.addEventListener("change", function () {
                    if (this.checked) {
                        showCard(index);
                    }
                });
            });
        }
    }

    // Initialize when modal is shown
    document.querySelectorAll(".booking-modal").forEach(modal => {
        modal.addEventListener("shown.bs.modal", function () {
            const wraps = modal.querySelectorAll(".car-card-wrap");
            wraps.forEach(initCarCards);
        });
    });
});




document.addEventListener("DOMContentLoaded", function () {
    document.querySelectorAll(".extra-options").forEach(section => {
        section.addEventListener("click", function (e) {
            if (e.target.classList.contains("plus") || e.target.classList.contains("minus")) {
                const input = e.target.parentElement.querySelector("input[type='number']");
                let value = parseInt(input.value) || 0;
                if (e.target.classList.contains("plus")) {
                    input.value = value + 1;
                } else if (e.target.classList.contains("minus") && value > 0) {
                    input.value = value - 1;
                }
            }
        });
    });

});

document.addEventListener("DOMContentLoaded", function () {
    const bookingForms = document.querySelectorAll('.booking-form');
    const successModal = new bootstrap.Modal(document.getElementById('globalSuccessModal'));

    bookingForms.forEach(form => {
        form.addEventListener('submit', function (e) {
            e.preventDefault();

            // Find the modal that contains this form
            const parentModal = form.closest('.modal');
            if (parentModal) {
                const modalInstance = bootstrap.Modal.getInstance(parentModal);
                if (modalInstance) modalInstance.hide();
            }

            // Show success modal after short delay for smoothness
            setTimeout(() => successModal.show(), 400);
        });
    });
});


document.addEventListener('DOMContentLoaded', () => {
    const sections = document.querySelectorAll('[data-grid]');
    if (!sections.length) return;

    sections.forEach((el) => {
        if (el.dataset.gridBound) return;
        el.dataset.gridBound = 'true';

        const getCell = () => parseFloat(getComputedStyle(el).getPropertyValue('--cell')) || 80;

        let lastGX = null, lastGY = null, lastT = 0;
        const throttleMs = 55;
        const MAX_PINGS = 16;
        const pool = [];

        function spawnPing(gx, gy) {
            const s = document.createElement('div');
            s.className = 'ping';
            s.style.setProperty('--x', `${gx}px`);
            s.style.setProperty('--y', `${gy}px`);
            el.appendChild(s);
            pool.push(s);

            // remove when animation completes (or after 3s as a fallback)
            const cleanup = () => { s.removeEventListener('animationend', cleanup); s.remove(); };
            s.addEventListener('animationend', cleanup);
            setTimeout(() => s.remove(), 3000);

            // ✅ cap pool size by removing the OLDEST PING (not the parent!)
            while (pool.length > MAX_PINGS) {
                const old = pool.shift();
                if (old) old.remove();      // <-- this was old.parentNode.remove() (bad)
            }
        }

        function onMove(e) {
            const now = performance.now();
            if (now - lastT < throttleMs) return;

            const r = el.getBoundingClientRect();
            const clientX = e.clientX ?? e.touches?.[0]?.clientX;
            const clientY = e.clientY ?? e.touches?.[0]?.clientY;
            if (clientX == null || clientY == null) return;

            const x = clientX - r.left;
            const y = clientY - r.top;
            const cell = getCell();

            const gx = Math.floor(x / cell) * cell;
            const gy = Math.floor(y / cell) * cell;
            if (gx === lastGX && gy === lastGY) return;

            spawnPing(gx, gy);
            lastGX = gx; lastGY = gy; lastT = now;
        }

        el.addEventListener('pointermove', onMove, { passive: true });
        el.addEventListener('touchmove', onMove, { passive: true });
    });
});


// Loader

(function () {
    const pre = document.getElementById('ax-preloader');
    if (!pre) return;

    const MIN_TIME = 600; // ms
    const start = performance.now();

    function hide() {
        const elapsed = performance.now() - start;
        const wait = Math.max(0, MIN_TIME - elapsed);
        setTimeout(() => pre.classList.add('ax--hidden'), wait);
    }

    window.addEventListener('load', hide);
    setTimeout(hide, 3000); // fallback
})();


document.addEventListener("DOMContentLoaded", function () {
    const cards = document.querySelectorAll(".membership-card");

    if (!cards || cards.length === 0) {
        return;
    }

    cards.forEach(card => {

        const readMore = card.querySelector(".benifit-read-more");
        const area = card.querySelector(".benifits-area");

        if (!readMore || !area) {
            return;
        }

        const originalText = readMore.innerHTML;

        area.classList.remove("open");

        readMore.addEventListener("click", () => {
            const isOpening = !area.classList.contains("open");

            area.classList.toggle("open");

            if (isOpening) {
                readMore.innerHTML = "Click to close";
            } else {
                readMore.innerHTML = originalText;
            }
        });
    });
});



// =========================
// FAQ Custom Accordion JS
// =========================
document.addEventListener("DOMContentLoaded", () => {

    const faqWrap = document.querySelector(".faq-wrap");
    if (!faqWrap) return;

    const items = faqWrap.querySelectorAll(".faq-item");
    if (!items.length) return;

    const setItemState = (item, open) => {
        const btn = item.querySelector(".faq-q");
        const panel = item.querySelector(".faq-a");

        if (!btn || !panel) return;

        if (open) {
            item.classList.add("is-open");
            btn.setAttribute("aria-expanded", "true");

            panel.style.height = panel.scrollHeight + "px";

            panel.addEventListener("transitionend", function handler(e) {
                if (e.propertyName === "height" && item.classList.contains("is-open")) {
                    panel.style.height = "auto";
                }
                panel.removeEventListener("transitionend", handler);
            });

        } else {
            item.classList.remove("is-open");
            btn.setAttribute("aria-expanded", "false");

            if (panel.style.height === "auto") {
                panel.style.height = panel.scrollHeight + "px";
            }
            void panel.offsetHeight;
            panel.style.height = "0px";
        }
    };

    items.forEach(item => {
        const btn = item.querySelector(".faq-q");
        const panel = item.querySelector(".faq-a");
        if (!btn || !panel) return;

        if (item.classList.contains("is-open")) {
            btn.setAttribute("aria-expanded", "true");
            panel.style.height = panel.scrollHeight + "px";
            requestAnimationFrame(() => (panel.style.height = "auto"));
        } else {
            btn.setAttribute("aria-expanded", "false");
            panel.style.height = "0px";
        }
    });

    items.forEach(item => {
        const btn = item.querySelector(".faq-q");
        if (!btn) return;

        btn.addEventListener("click", () => {
            const isOpen = item.classList.contains("is-open");

            items.forEach(i => {
                if (i !== item) setItemState(i, false);
            });

            setItemState(item, !isOpen);
        });
    });

    window.addEventListener("resize", () => {
        items.forEach(item => {
            if (item.classList.contains("is-open")) {
                const panel = item.querySelector(".faq-a");
                if (panel) panel.style.height = "auto";
            }
        });
    });
});