(function () {
  'use strict';

  var config = window.misticeaseHdThumbPrefetchConfig || null;

  if (!config) {
    var dataEl = document.getElementById('misticease-hd-thumb-prefetch-data');
    if (!dataEl) {
      return;
    }

    try {
      config = JSON.parse(dataEl.textContent || '{}');
    } catch (error) {
      return;
    }
  }

  var items = Array.isArray(config.items) ? config.items : [];
  var ajaxUrl = typeof config.ajaxUrl === 'string' ? config.ajaxUrl : '';
  var maxConcurrent = Number(config.maxConcurrent) || 2;
  var nonce = typeof config.nonce === 'string' ? config.nonce : '';

  if (!items.length || !ajaxUrl) {
    return;
  }

  var seen = Object.create(null);
  var queue = [];

  for (var i = 0; i < items.length; i += 1) {
    var item = items[i] || {};
    var service = typeof item.service === 'string' ? item.service : '';
    var videoId = typeof item.video_id === 'string' ? item.video_id : '';
    var token = typeof item.token === 'string' ? item.token : '';
    var key = service + '|' + videoId;

    if (!service || !videoId || !token || seen[key]) {
      continue;
    }

    seen[key] = true;
    queue.push({ service: service, video_id: videoId, token: token });
  }

  if (!queue.length) {
    return;
  }

  var active = 0;

  function done() {
    active -= 1;
    if (active < 0) {
      active = 0;
    }
    pump();
  }

  function postOne(entry) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', ajaxUrl, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        done();
      }
    };
    xhr.onerror = done;
    xhr.send(
      'action=misticease_hd_thumb_prefetch' +
        '&service=' + encodeURIComponent(entry.service) +
        '&video_id=' + encodeURIComponent(entry.video_id) +
        '&token=' + encodeURIComponent(entry.token) +
        '&nonce=' + encodeURIComponent(nonce)
    );
  }

  function pump() {
    while (active < maxConcurrent && queue.length) {
      active += 1;
      postOne(queue.shift());
    }
  }

  function start() {
    pump();
  }

  if (document.readyState === 'complete') {
    setTimeout(start, 0);
  } else {
    window.addEventListener('load', function () {
      setTimeout(start, 0);
    }, { once: true });
  }
})();