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

  function element() {
    return $('#poi-audio')[0];
  }

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

  function unload() {
    const audio = element();
    audio.pause();
    audio.removeAttribute('src');
    audio.load();
    $(audio).attr('hidden', '').hide();
  }

  ns.AudioPlayer = {
    load(url) {
      unload();
      if (!url) return;

      const audio = element();
      audio.src = mediaUrl(url);
      $(audio).removeAttr('hidden').css('display', 'block');
      audio.load();
    },

    play() {
      const audio = element();
      if (audio.getAttribute('src')) return audio.play();
      return Promise.resolve();
    },

    pause() {
      element().pause();
    },

    unload
  };
}(globalThis.Wegwichtel, globalThis.jQuery));
