const mobileViewport = window.matchMedia("(max-width: 640px)");

const initializeCarousel = (carousel) => {
    const cards = Array.from(carousel.querySelectorAll(".recent-posts__card"));
    const dots = Array.from(carousel.querySelectorAll(".recent-posts__dot"));
    const previous = carousel.querySelector(".recent-posts__control--previous");
    const next = carousel.querySelector(".recent-posts__control--next");

    if (cards.length < 2 || !previous || !next) {
        return;
    }

    let activeIndex = 0;

    const render = () => {
        cards.forEach((card, index) => {
            const isActive = index === activeIndex;
            card.classList.toggle("is-active", isActive);
            card.hidden = mobileViewport.matches && !isActive;
        });

        dots.forEach((dot, index) => {
            const isActive = index === activeIndex;
            dot.classList.toggle("is-active", isActive);
            dot.toggleAttribute("aria-current", isActive);
        });
    };

    const showArticle = (index) => {
        activeIndex = (index + cards.length) % cards.length;
        render();
    };

    previous.addEventListener("click", () => showArticle(activeIndex - 1));
    next.addEventListener("click", () => showArticle(activeIndex + 1));
    dots.forEach((dot, index) =>
        dot.addEventListener("click", () => showArticle(index)),
    );
    mobileViewport.addEventListener("change", render);

    render();
};

const initRecentPostsCarousels = () => {
    document.querySelectorAll(".recent-posts").forEach(initializeCarousel);
};

export default initRecentPostsCarousels;
