<script>
  var disqus_config = function () {
    this.page.url = '{{ page.url | absolute_url }}';
    this.page.identifier = '{{ page.url }}';
  };

  function addDisqus() {
    let disqusThread = document.createElement('div');
    let paragraph = document.createElement('p');

    disqusThread.id = 'disqus_thread';
    paragraph.className = 'text-center text-muted small';
    paragraph.innerHTML = 'Comments powered by <a href="https://disqus.com/">Disqus</a>.';
    disqusThread.appendChild(paragraph);

    const footer = document.querySelector('footer');
    footer.insertAdjacentElement("beforebegin", disqusThread);
  }

  {%- comment -%} Auto switch theme {%- endcomment -%}
  function reloadDisqus(event) {
    if (event.source === window && event.data && event.data.id === Theme.ID) {
      {%- comment -%} Disqus hasn't been loaded {%- endcomment -%}
      if (typeof DISQUS === 'undefined') {
        return;
      }

      if (document.readyState == 'complete') {
        DISQUS.reset({ reload: true, config: disqus_config });
      }
    }
  }

  addDisqus();

  if (Theme.switchable) {
    addEventListener('message', reloadDisqus);
  }

  {%- comment -%} Lazy loading {%- endcomment -%}
  var disqusObserver = new IntersectionObserver(
    function (entries) {
      if (entries[0].isIntersecting) {
        var d = document,
          s = d.createElement('script');
        s.src = 'https://{{ site.comments.disqus.shortname }}.disqus.com/embed.js';
        s.setAttribute('data-timestamp', +new Date());
        (d.head || d.body).appendChild(s);

        disqusObserver.disconnect();
      }
    },
    { threshold: [0] }
  );

  disqusObserver.observe(document.getElementById('disqus_thread'));
</script>
