import { InobyModule } from "@lib/inoby-module";
import GLightbox from "glightbox";
import * as $ from "jquery";
import KeenSlider from "keen-slider";
import { dots, adaptiveHeight, arrows } from "@lib/keen-slider-plugins";
import KeenSliderHelper from "@assets/js/lib/keen-slider-helper";

class ProductSingleModule extends InobyModule {
  run() {
    if ($(document.body).hasClass("single-product")) {
      this.initProductGallery();
    }
  }

  initProductGallery(): void {
    // replace HTML attrbites on element
    const replaceAttrs = (el: Element, newEl: Element, children = true) => {
      newEl.getAttributeNames().forEach((attr) => {
        el.setAttribute(attr, newEl.getAttribute(attr));
        if (children && el.firstChild && newEl.firstChild) {
          replaceAttrs(el.firstElementChild, newEl.firstElementChild, children);
        }
      });
    };

    // collect all gallery image sources
    const getGalleryElements = () => {
      return $(".woocommerce-product-gallery .slider .woocommerce-product-gallery__image img")
        .map((i, el) => {
          return { href: el.dataset.large_image };
        })
        .toArray();
    };

    // init popup gallery
    const popup = GLightbox({
      elements: getGalleryElements(),
      slideEffect: "fade",
    });

    // init mobile slider
    const mobileSlider = new KeenSlider(
      ".woocommerce-product-gallery .slider",
      {
        selector: ".woocommerce-product-gallery__image",
      },
      [dots, adaptiveHeight, arrows]
    );

    // replace master image on variation change
    $(document).on("found_variation hide_variation", () => {
      const newMaster = document.querySelector(".woocommerce-product-gallery .master-image .woocommerce-product-gallery__image");
      const sliderMasterImage = document.querySelector(".woocommerce-product-gallery .slider .woocommerce-product-gallery__image");
      const galleryMasterImage = document.querySelector(".woocommerce-product-gallery .gallery .woocommerce-product-gallery__image");

      [sliderMasterImage, galleryMasterImage].forEach((oldMaster) => replaceAttrs(oldMaster, newMaster));

      setTimeout(() => {
        // trigger slider update and move to first slide
        mobileSlider.update(undefined, 0);
        // set new elements to popup gallery
        popup.setElements(getGalleryElements());
      }, 20);
    });

    // prevent clicking on image links
    $(document).on("click", ".woocommerce-product-gallery__image", (e) => e.preventDefault());

    // open gallery on master-image/thumbs clicks
    $(document).on("click", ".gallery .woocommerce-product-gallery__image", (e) => {
      let idx = 0;
      if ($(e.target).hasClass("woocommerce-product-gallery__image")) {
        idx = $(e.target).data("gallery-index");
      } else {
        idx = $(e.target).parents(".woocommerce-product-gallery__image").data("gallery-index");
      }

      popup.openAt(idx);
    });
  }
}

class UpSellProductsSlieder extends InobyModule {
  run() {
    const $sliderContainer = $("[id^=up-sell-slider]");
    $sliderContainer.removeClass("row").addClass("keen-slider");
    KeenSliderHelper.registerSlider(
      $sliderContainer,
      {
        selector: ".content-product-wrap",
        loop: true,
        origin: "auto",
        slides: {
          perView: 4,
          spacing: 30,
        },
        breakpoints: {
          "(min-width: 320px)": {
            slides: {
              perView: 1.5,
              spacing: 15,
              mode: "free",
            },
          },
          "(min-width: 576px)": {
            slides: {
              perView: 1.5,
              spacing: 30,
              mode: "free",
            },
          },
          "(min-width: 768px)": {
            slides: {
              perView: 2.5,
              spacing: 30,
            },
          },
          "(min-width: 1200px)": {
            slides: {
              perView: 4.5,
              spacing: 30,
              origin: "auto",
            },
          },
        },
      },
      true
    );
  }
}

class RelatedProductsSlieder extends InobyModule {
  run() {
    const $sliderContainer = $("[id^=related-slider]");
    $sliderContainer.removeClass("row").addClass("keen-slider");
    KeenSliderHelper.registerSlider(
      $sliderContainer,
      {
        selector: ".content-product-wrap",
        loop: true,
        slides: {
          perView: 4,
          spacing: 30,
        },
        breakpoints: {
          "(min-width: 320px)": {
            slides: {
              perView: 1.5,
              spacing: 15,
              mode: "free",
            },
          },
          "(min-width: 576px)": {
            slides: {
              perView: 1.5,
              spacing: 30,
              mode: "free",
            },
          },
          "(min-width: 768px)": {
            slides: {
              perView: 2.5,
              spacing: 30,
            },
          },
          "(min-width: 1200px)": {
            slides: {
              perView: 4.2,
              spacing: 30,
              origin: "auto",
            },
          },
        },
      },
      true
    );
  }
}

new ProductSingleModule().runOnReady();

new RelatedProductsSlieder().runOnReady();

new UpSellProductsSlieder().runOnReady();
