import './style.css';

const toNumber = (value, fallback = 0) => {
  const parsed = Number.parseInt(String(value), 10);
  return Number.isFinite(parsed) ? parsed : fallback;
};

const isEnabled = (value) => value === 'yes' || value === true || value === 'true' || value === '1';

const getSwiperConstructor = () => {
  if (typeof window.Swiper === 'function') {
    return window.Swiper;
  }

  if (typeof window.Swiper?.default === 'function') {
    return window.Swiper.default;
  }

  return null;
};

const syncActiveSlide = (slider, swiper) => {
  const highlightActive = isEnabled(slider.dataset.highlightActive);
  swiper.slides.forEach((slide) => slide.classList.remove('is-active-slide'));

  if (!highlightActive) {
    return;
  }

  const active = swiper.slides?.[swiper.activeIndex];
  if (active) {
    active.classList.add('is-active-slide');
  }
};

const refreshSwiper = (swiper) => {
  if (!swiper || swiper.destroyed) {
    return;
  }

  swiper.update();
  swiper.navigation?.update?.();
  swiper.pagination?.render?.();
  swiper.pagination?.update?.();
  swiper.scrollbar?.updateSize?.();
};

const updateWhenImagesLoad = (slider, swiper) => {
  slider.querySelectorAll('img').forEach((image) => {
    if (image.complete) {
      return;
    }

    image.addEventListener('load', () => refreshSwiper(swiper), { once: true });
    image.addEventListener('error', () => refreshSwiper(swiper), { once: true });
  });
};

const initWooSlider = (root) => {
  root.querySelectorAll('.calio-woo-slider').forEach((slider) => {
    const swiperElement = slider.querySelector('.calio-woo-slider-swiper');
    const SwiperConstructor = getSwiperConstructor();
    if (!swiperElement || !SwiperConstructor) {
      return;
    }

    if (slider.__calioWooSlider && typeof slider.__calioWooSlider.destroy === 'function') {
      slider.__calioWooSlider.destroy(true, true);
      slider.__calioWooSlider = null;
    }

    const spaceBetween = Math.max(0, toNumber(slider.dataset.spaceBetween, 24));
    const slidesDesktop = Math.max(1, toNumber(slider.dataset.slidesDesktop, 4));
    const slidesTablet = Math.max(1, toNumber(slider.dataset.slidesTablet, 2));
    const slidesMobile = Math.max(1, toNumber(slider.dataset.slidesMobile, 1));
    const slidesScroll = Math.max(1, toNumber(slider.dataset.slidesScroll, 1));
    const speed = Math.max(100, toNumber(slider.dataset.transitionSpeed, 600));
    const autoplaySpeed = Math.max(1000, toNumber(slider.dataset.autoplaySpeed, 3500));

    const showArrows = isEnabled(slider.dataset.showArrows);
    const showDots = isEnabled(slider.dataset.showDots);
    const showScrollbar = isEnabled(slider.dataset.showScrollbar);
    const autoplay = isEnabled(slider.dataset.autoplay);
    const pauseOnHover = isEnabled(slider.dataset.pauseOnHover);
    const pauseOnInteraction = isEnabled(slider.dataset.pauseOnInteraction);
    const loop = isEnabled(slider.dataset.loop);
    const grabCursor = isEnabled(slider.dataset.grabCursor);
    const centeredSlides = isEnabled(slider.dataset.centeredSlides);

    const prev = showArrows ? slider.querySelector('.calio-woo-slider-arrow.is-prev') : null;
    const next = showArrows ? slider.querySelector('.calio-woo-slider-arrow.is-next') : null;
    const pagination = showDots ? slider.querySelector('.calio-woo-slider-pagination') : null;
    const scrollbar = showScrollbar ? slider.querySelector('.calio-woo-slider-scrollbar') : null;

    const instance = new SwiperConstructor(swiperElement, {
      observer: true,
      observeParents: true,
      watchOverflow: true,
      loop,
      speed,
      grabCursor,
      centeredSlides,
      spaceBetween,
      slidesPerView: slidesDesktop,
      slidesPerGroup: slidesScroll,
      autoplay: autoplay
        ? {
            delay: autoplaySpeed,
            disableOnInteraction: pauseOnInteraction,
            pauseOnMouseEnter: pauseOnHover,
          }
        : false,
      navigation: prev && next ? { prevEl: prev, nextEl: next } : false,
      pagination: pagination
        ? {
            el: pagination,
            clickable: true,
          }
        : false,
      scrollbar: scrollbar
        ? {
            el: scrollbar,
            draggable: true,
          }
        : false,
      breakpoints: {
        0: {
          slidesPerView: slidesMobile,
          slidesPerGroup: 1,
        },
        768: {
          slidesPerView: slidesTablet,
          slidesPerGroup: Math.min(slidesScroll, slidesTablet),
        },
        1025: {
          slidesPerView: slidesDesktop,
          slidesPerGroup: Math.min(slidesScroll, slidesDesktop),
        },
      },
      on: {
        init(swiper) {
          syncActiveSlide(slider, swiper);
          window.requestAnimationFrame(() => refreshSwiper(swiper));
        },
        slideChange(swiper) {
          syncActiveSlide(slider, swiper);
        },
        resize(swiper) {
          syncActiveSlide(slider, swiper);
        },
      },
    });

    syncActiveSlide(slider, instance);
    updateWhenImagesLoad(slider, instance);
    window.setTimeout(() => refreshSwiper(instance), 120);
    window.setTimeout(() => refreshSwiper(instance), 600);
    slider.__calioWooSlider = instance;
  });
};

const boot = (scope = document) => {
  const root = scope instanceof HTMLElement || scope instanceof Document ? scope : document;
  initWooSlider(root);
};

const bootWhenReady = (scope = document) => {
  const run = () => boot(scope);

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', run, { once: true });
  } else {
    run();
  }

  let attempts = 0;
  const timer = window.setInterval(() => {
    attempts += 1;
    boot(scope);

    if (getSwiperConstructor() || attempts >= 20) {
      window.clearInterval(timer);
    }
  }, 250);

  window.addEventListener('load', run, { once: true });
};

bootWhenReady(document);

let calioWooSliderHookBound = false;
const bindElementorWooSlider = () => {
  if (calioWooSliderHookBound) {
    return true;
  }

  if (!window.elementorFrontend?.hooks) {
    return false;
  }

  window.elementorFrontend.hooks.addAction('frontend/element_ready/calio-woocommerce-slider.default', ($scope) => {
    const root = $scope?.[0] || document;
    bootWhenReady(root);
  });

  calioWooSliderHookBound = true;
  return true;
};

window.addEventListener('elementor/frontend/init', bindElementorWooSlider);
if (!bindElementorWooSlider()) {
  let attempts = 0;
  const timer = window.setInterval(() => {
    attempts += 1;
    if (bindElementorWooSlider() || attempts >= 40) {
      window.clearInterval(timer);
    }
  }, 250);
}
