(function ($) {
	$.fn.ninodemSlick = function (opts) {
	  const defaults = {
		infinite: true,
		slidesToShow: 1,
		slidesToScroll: 1,
		adaptiveHeight: false,
		overflow: 0,
		responsive: []
	  };

	  const settings = $.extend(true, {}, defaults, opts);
	  const respSortedAsc = settings.responsive.slice().sort((a, b) => a.breakpoint - b.breakpoint);

	  return this.each(function () {
		const $slider = $(this);

		$slider.slick({
		  infinite: settings.infinite,
		  slidesToShow: settings.slidesToShow,
		  slidesToScroll: settings.slidesToScroll,
		  adaptiveHeight: settings.adaptiveHeight,
		  centerMode: false,
		  responsive: settings.responsive.map(r => ({
			breakpoint: r.breakpoint,
			settings: {
			  slidesToShow: r.settings.slidesToShow ?? settings.slidesToShow,
			  centerMode: false
			}
		  })),
		});

		function getCurrentOverflow() {
		  const w = window.innerWidth;
		  for (const resp of respSortedAsc) {
			if (w < resp.breakpoint && resp.settings.overflow != null) {
			  return resp.settings.overflow;
			}
		  }
		  return settings.overflow;
		}

		function getCurrentSlidesToShow() {
		  const w = window.innerWidth;
		  for (const resp of respSortedAsc) {
			if (w < resp.breakpoint && resp.settings.slidesToShow != null) {
			  return resp.settings.slidesToShow;
			}
		  }
		  return settings.slidesToShow;
		}

		function updatePeek() {
		  const visible = getCurrentSlidesToShow();
		  const overflow = getCurrentOverflow();

		  const $first = $slider.find('.slick-slide').first();
		  const gap = parseInt($first.css('margin-right'), 10) || 0;
		  const containerW = $slider.width();
		  const slideW = containerW / (visible + overflow);

		  const roundedSlideW = Math.round(slideW);
		  const peekPx = roundedSlideW * overflow;
		  const rawTotal = peekPx + gap;
		  const totalPeek = (Math.abs(rawTotal - Math.round(rawTotal)) < 0.01)
			? Math.round(rawTotal)
			: parseFloat(rawTotal.toFixed(6));

		  const $list = $slider.find('.slick-list');

		  $slider.find('.slick-slide').css('width', `${roundedSlideW}px`);
		  $slider.css('--ninodem--slick-slide--card-overflow', `${totalPeek}px`);
		  $list.css({
			'padding-right': 'var(--ninodem--slick-slide--card-overflow)',
			'overflow': 'visible'
		  });

		  $slider.slick('slickSetOption', 'slidesToShow', visible, false);
		}

		$slider.on('setPosition', updatePeek);
		$(window).on('load resize', updatePeek);

		return $slider;
	  });
	};
  })(jQuery);
