// Menu
const header = document.querySelector(".site-header");
const menuButton = document.querySelector(".menu-button");
const menuLinks = document.querySelectorAll(".desktop-nav a");

menuButton.addEventListener("click", () => {
  const menuIsOpen = header.classList.toggle("is-menu-open");

  menuButton.setAttribute("aria-expanded", menuIsOpen);
  menuButton.setAttribute("aria-label", menuIsOpen ? "Close menu" : "Open menu");
});

menuLinks.forEach((link) => {
  link.addEventListener("click", () => {
    header.classList.remove("is-menu-open");
    menuButton.setAttribute("aria-expanded", "false");
    menuButton.setAttribute("aria-label", "Open menu");
  });
});

// Carousel wheel
const productCards = document.querySelectorAll(".product-card");
const prevButton = document.querySelector(".prev-button");
const nextButton = document.querySelector(".next-button");
let currentCard = 0;

function showCard() {
  productCards.forEach((card) => {
    card.classList.remove("active");
  });

  productCards[currentCard].classList.add("active");
}

nextButton.addEventListener("click", () => {
  currentCard = currentCard === productCards.length - 1 ? 0 : currentCard + 1;
  showCard();
});

prevButton.addEventListener("click", () => {
  currentCard = currentCard === 0 ? productCards.length - 1 : currentCard - 1;
  showCard();
});

showCard();

// Text animations
async function startTextAnimation() {
  try {
    const { animate, stagger, splitText } = await import("https://esm.sh/animejs");

    const { chars: blendChars } = splitText(".section-heading p", {
      words: false,
      chars: true,
    });

    animate(blendChars, {
      y: [
        { to: "-1rem", ease: "outExpo", duration: 600 },
        { to: 0, ease: "outBounce", duration: 800, delay: 100 },
      ],
      delay: stagger(50),
      ease: "inOutCirc",
      loopDelay: 1000,
      loop: true,
    });
  } catch (error) {
    console.log("Anime.js did not load, but the menu and carousel still work.");
  }
}

startTextAnimation();
