(() => {
  "use strict";
  const viewer = document.getElementById("projectViewer");
  const frame = document.getElementById("viewerFrame");
  if (!viewer || !frame) return;
  frame.setAttribute("scrolling", "yes");
  frame.setAttribute("tabindex", "0");
  const focusFrame = () => {
    try { frame.focus({preventScroll:true}); } catch (_) { frame.focus(); }
    try { frame.contentWindow?.focus(); } catch (_) {}
  };
  frame.addEventListener("load", () => {
    setTimeout(focusFrame, 80);
    setTimeout(() => {
      try { frame.contentWindow?.postMessage({type:"APU_PROJECT_SCROLL_TO",top:0,behavior:"auto"},"*"); } catch (_) {}
    }, 120);
  });
  viewer.addEventListener("click", event => {
    if (event.target === frame || event.target.closest?.("iframe")) focusFrame();
  });
  document.addEventListener("keydown", event => {
    if (!viewer.open || event.defaultPrevented) return;
    if (event.target?.matches?.("input,textarea,select,[contenteditable='true']")) return;
    const amount = Math.max(100, frame.clientHeight * .86);
    let message = null;
    if (event.key === "PageDown" || (event.key === " " && !event.shiftKey)) message={type:"APU_PROJECT_SCROLL_BY",top:amount,behavior:"smooth"};
    else if (event.key === "PageUp" || (event.key === " " && event.shiftKey)) message={type:"APU_PROJECT_SCROLL_BY",top:-amount,behavior:"smooth"};
    else if (event.key === "End") message={type:"APU_PROJECT_SCROLL_END",behavior:"smooth"};
    else if (event.key === "Home") message={type:"APU_PROJECT_SCROLL_TO",top:0,behavior:"smooth"};
    if (message) {
      event.preventDefault();
      try { frame.contentWindow?.postMessage(message,"*"); } catch (_) {}
    }
  }, {capture:true});
})();
