(function (ns, $) {
  'use strict';

  let images = [];
  let index = 0;
  let swipe = null;

  function mediaUrl(url) {
    if (!url) return '';
    const separator = url.includes('?') ? '&' : '?';
    return `${url}${separator}v=${Date.now()}`;
  }

  function activate(selector, handler) {
    $(document)
      .on('pointerup', selector, function (event) {
        const pointer = event.originalEvent;
        if (pointer?.isPrimary === false) return;
        if (pointer?.pointerType === 'mouse' && pointer.button !== 0) return;
        event.preventDefault();
        handler.call(this, event);
      })
      .on('keydown', selector, function (event) {
        if (event.key !== 'Enter' && event.key !== ' ') return;
        event.preventDefault();
        handler.call(this, event);
      });
  }

  function refreshButton(selector, disabled) {
    const button = $(selector).prop('disabled', disabled);
    if (button.hasClass('ui-button')) button.button('refresh');
  }

  function render() {
    const hasImages = images.length > 0;
    $('#slideshow').toggle(hasImages);
    if (!hasImages) return;

    const image = images[index];
    $('#slide-image')
      .attr('src', mediaUrl(image.url))
      .attr('alt', image.caption || 'Bild zur Station')
      .off('error.wegwichtel')
      .on('error.wegwichtel', function () {
        $(this).removeAttr('src').attr('alt', 'Bild konnte nicht geladen werden');
      });
    $('#slide-caption').text(image.caption || '');
    $('#slide-position').text(`${index + 1} / ${images.length}`);
    refreshButton('#slide-prev', images.length < 2);
    refreshButton('#slide-next', images.length < 2);
  }

  ns.Slideshow = {
    show(items) {
      images = items || [];
      index = 0;
      render();
    },

    next() {
      if (images.length) index = (index + 1) % images.length;
      render();
    },

    previous() {
      if (images.length) index = (index - 1 + images.length) % images.length;
      render();
    }
  };

  activate('#slide-next', () => ns.Slideshow.next());
  activate('#slide-prev', () => ns.Slideshow.previous());

  $(document)
    .on('pointerdown', '#slideshow', function (event) {
      if ($(event.target).closest('button').length) return;
      const pointer = event.originalEvent;
      if (!pointer?.isPrimary) return;
      swipe = { id: pointer.pointerId, x: pointer.clientX, y: pointer.clientY };
    })
    .on('pointerup pointercancel', '#slideshow', function (event) {
      const pointer = event.originalEvent;
      if (!swipe || pointer?.pointerId !== swipe.id) return;
      if (event.type === 'pointercancel') {
        swipe = null;
        return;
      }

      const deltaX = pointer.clientX - swipe.x;
      const deltaY = pointer.clientY - swipe.y;
      swipe = null;

      if (Math.abs(deltaX) < 45 || Math.abs(deltaX) <= Math.abs(deltaY)) return;
      if (deltaX < 0) ns.Slideshow.next();
      else ns.Slideshow.previous();
    });
}(globalThis.Wegwichtel, globalThis.jQuery));
