(function () {
  'use strict';

  var bar       = document.getElementById('readjutsu-progress-bar');
  var container = document.getElementById('readjutsu-progress');

  if (!bar || !container) return;

  var isVertical     = typeof READJUTSU !== 'undefined' && READJUTSU.orientation === 'vertical';
  var prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  var ticking = false;
  var idleTimer;

  function getContentEl() {
    var marker = document.getElementById('readjutsu-marker');
    if (marker && marker.parentElement) {
      return marker.parentElement;
    }
    return (
      document.querySelector('.wp-block-post-content') ||
      document.querySelector('.entry-content') ||
      document.querySelector('.post-content') ||
      document.body
    );
  }

  function getTrackingEl() {
    if (typeof READJUTSU !== 'undefined' && READJUTSU.scope === 'page') {
      return document.body;
    }
    return getContentEl();
  }

  function updateBar() {
    var content   = getTrackingEl();
    var scrollTop = window.pageYOffset;
    // Document-absolute top (offsetTop is relative to offsetParent only).
    var start     = content.getBoundingClientRect().top + scrollTop;
    // Scroll distance between "content top at viewport top" and "content
    // bottom at viewport bottom" — the denominator must NOT include start,
    // otherwise the bar can never reach 100%.
    var total     = content.offsetHeight - window.innerHeight;

    var pct = total <= 0 ? 100 : Math.min(100, Math.max(0, ((scrollTop - start) / total) * 100));

    if (isVertical) {
      bar.style.height = pct + '%';
    } else {
      bar.style.width = pct + '%';
    }

    bar.setAttribute('aria-valuenow', Math.round(pct));
    ticking = false;
  }

  function onScroll() {
    if (!ticking) {
      requestAnimationFrame(updateBar);
      ticking = true;
    }
    resetIdle();
  }

  function goIdle() {
    container.style.opacity = '0.4';
  }
  function resetIdle() {
    container.style.opacity = '1';
    clearTimeout(idleTimer);
    idleTimer = setTimeout(goIdle, 2000);
  }

  window.addEventListener('scroll',     onScroll, { passive: true });
  window.addEventListener('touchmove',  onScroll, { passive: true });

  updateBar();
  resetIdle();
})();
