// Lazy-load asciinema-player from a CDN only on pages that have a
// .asciinema-player div. Avoids loading the player on every page.

(function () {
  function load() {
    const targets = document.querySelectorAll('.asciinema-player[data-src]');
    if (!targets.length) return;

    const PLAYER_CSS =
      'https://cdn.jsdelivr.net/npm/asciinema-player@3.7.0/dist/bundle/asciinema-player.min.css';
    const PLAYER_JS =
      'https://cdn.jsdelivr.net/npm/asciinema-player@3.7.0/dist/bundle/asciinema-player.min.js';

    const css = document.createElement('link');
    css.rel = 'stylesheet';
    css.href = PLAYER_CSS;
    document.head.appendChild(css);

    const js = document.createElement('script');
    js.src = PLAYER_JS;
    js.onload = function () {
      targets.forEach((el) => {
        const src = el.getAttribute('data-src');
        const opts = {
          autoPlay: el.getAttribute('data-autoplay') === 'true',
          loop: el.getAttribute('data-loop') === 'true',
          theme: el.getAttribute('data-theme') || 'asciinema',
          fit: el.getAttribute('data-fit') || 'width',
          idleTimeLimit: 2,
        };
        // eslint-disable-next-line no-undef
        AsciinemaPlayer.create(src, el, opts);
      });
    };
    document.head.appendChild(js);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', load);
  } else {
    load();
  }
})();
