(function initMyronMediaPlayer(global) {
  "use strict";

  function onReady(callback) {
    if (global.document.readyState === "loading") {
      global.document.addEventListener("DOMContentLoaded", callback, { once: true });
      return;
    }

    callback();
  }

  function setupQualityControls() {
    var bars = global.document.querySelectorAll("[data-myron-media-quality]");
    bars.forEach(function bindQualityBar(bar) {
      var preview = bar.closest(".mc-side-sheet__preview");
      var video = preview ? preview.querySelector("[data-myron-media-player]") : null;
      if (!video) {
        return;
      }

      bar.querySelectorAll("[data-src]").forEach(function bindButton(button, index) {
        if (index === 0) {
          button.setAttribute("aria-pressed", "true");
        }

        button.addEventListener("click", function onQualityClick() {
          var src = button.getAttribute("data-src") || "";
          if (!src || video.currentSrc === src || video.getAttribute("src") === src) {
            return;
          }

          var currentTime = video.currentTime || 0;
          var shouldPlay = !video.paused;
          video.pause();
          video.setAttribute("src", src);
          video.load();
          video.addEventListener("loadedmetadata", function restorePlayback() {
            if (currentTime > 0 && Number.isFinite(currentTime)) {
              video.currentTime = Math.min(currentTime, video.duration || currentTime);
            }
            if (shouldPlay) {
              video.play();
            }
          }, { once: true });

          bar.querySelectorAll("[data-src]").forEach(function sync(otherButton) {
            otherButton.setAttribute("aria-pressed", otherButton === button ? "true" : "false");
          });
        });
      });
    });
  }

  onReady(setupQualityControls);
})(window);
