const compareOwl = $(".pv-compare-slider");

compareOwl.owlCarousel({
  items: 1,
  loop: true,
  margin: 0,
  nav: true,
  dots: false,
  smartSpeed: 700,

  navText: [
    '<i class="fas fa-chevron-left"></i>',
    '<i class="fas fa-chevron-right"></i>',
  ],
});

document.querySelectorAll(".pv-compare").forEach((compare) => {
  const after = compare.querySelector(".pv-compare-after");
  const handle = compare.querySelector(".pv-compare-handle");

  let isDragging = false;

  function moveSlider(clientX) {
    const rect = compare.getBoundingClientRect();

    let percent = ((clientX - rect.left) / rect.width) * 100;

    percent = Math.max(0, Math.min(100, percent));

    after.style.clipPath = `inset(0 ${100 - percent}% 0 0)`;

    handle.style.left = percent + "%";
  }

  after.style.clipPath = "inset(0 50% 0 0)";
  handle.style.left = "50%";

  // START DRAG
  function startDrag(e) {
    isDragging = true;

    compareOwl.trigger("stop.owl.autoplay");

    compareOwl.addClass("compare-dragging");

    e.stopPropagation();
  }

  // END DRAG
  function stopDrag() {
    isDragging = false;

    compareOwl.removeClass("compare-dragging");
  }

  handle.addEventListener("mousedown", startDrag);

  handle.addEventListener("touchstart", startDrag, { passive: true });

  window.addEventListener("mouseup", stopDrag);

  window.addEventListener("touchend", stopDrag);

  window.addEventListener("mousemove", (e) => {
    if (!isDragging) return;

    moveSlider(e.clientX);
  });

  window.addEventListener(
    "touchmove",
    (e) => {
      if (!isDragging) return;

      moveSlider(e.touches[0].clientX);
    },
    { passive: true },
  );
});
