(() => {
  "use strict";

  function constrainActualOverflow() {
    if (innerWidth > 767) return;

    const viewport = document.documentElement.clientWidth;
    const candidates = document.querySelectorAll(
      "img,video,canvas,iframe,pre,table,dialog,[role='dialog']"
    );

    for (const element of candidates) {
      const rect = element.getBoundingClientRect();
      const style = getComputedStyle(element);
      const scrollable =
        style.overflowX === "auto" ||
        style.overflowX === "scroll";

      if (rect.width > viewport + 2 && !scrollable) {
        element.style.maxWidth = "100%";
        element.style.boxSizing = "border-box";
      }
    }
  }

  let pending = false;
  const schedule = () => {
    if (pending) return;
    pending = true;
    requestAnimationFrame(() => {
      pending = false;
      constrainActualOverflow();
    });
  };

  addEventListener("load", schedule, { once: true });
  addEventListener("resize", schedule, { passive: true });
  addEventListener("orientationchange", schedule, { passive: true });

  new MutationObserver(schedule).observe(document.documentElement, {
    childList: true,
    subtree: true
  });

  schedule();
})();
