/**
 * Internal depedencies
 */
import { EVENTS, triggerEvent } from "../../utils/dom";
import { addCarousel } from "./carousel-script";
import "./handle-video";
import "./preloader";

/**
 * Kick start the carousel on frontend.
 */
document.addEventListener("DOMContentLoaded", function () {
  let carouselElements = Array.from(
    document.querySelectorAll(".js-carousel-layout:not(.is-block-editor)"),
  );

  carouselElements.forEach((carouselElement, index) => {
    const instanceId = `cbb-carousel-${index + 1}`;
    const args = {
      instanceId,
    };

    if (!carouselElement.closest(".is-toggle-content")) {
      addCarousel(carouselElement, args, carouselElements);
    }

    carouselElement.addEventListener("cbb.carousel.start", () => {
      const instance = addCarousel(carouselElement, args, carouselElements);

      if (instance?.sliderOptions?.autoplay) {
        instance.slider.autoplay.start();
      }
    });

    carouselElement.addEventListener("cbb.carousel.pause", () => {
      const instance = addCarousel(carouselElement, args, carouselElements);
      if (instance?.slider?.autoplay?.running) {
        instance.slider.autoplay.pause();
      }
    });
  });
});

/**
 * Start carousel inside a toggle content.
 */
window.addEventListener(EVENTS.SHOWN, function ({ detail: { target } = {} }) {
  if (target) {
    target
      .querySelectorAll(".js-carousel-layout")
      .forEach((carousel) => triggerEvent(carousel, "cbb.carousel.start"));
  }
});
