// Mounts real Songbook Master app screens into the landing page's device slots,
// scales each iPad frame to fit its CSS-sized container, and keeps scale in sync
// on resize. Screen components are exposed on window by the imported jsx files.

(function () {
  const NATIVE_W = 800;   // IPadFrame total width  (768 + bezel 28 + 4)
  const NATIVE_H = 1052;  // IPadFrame total height (1024 + bezel 28)

  function ready() {
    return window.IPadFrame && window.SongDetail && window.PdfSongDetail &&
      window.ConversionProgress && window.SetlistLive && window.StageMode &&
      window.Folders && window.Library && window.SBM_LOGOS;
  }

  function fit(slot) {
    const scaleEl = slot.querySelector(".device-scale");
    const w = slot.clientWidth;
    if (!w || !scaleEl) return;
    scaleEl.style.zoom = w / NATIVE_W;  // zoom shrinks the layout box, keeping the grid intact
  }

  function build() {
    if (!ready()) return setTimeout(build, 40);

    const slots = [...document.querySelectorAll(".device[data-screen]")];
    slots.forEach((slot) => {
      const name = slot.dataset.screen;
      const Comp = window[name];
      const mount = slot.querySelector(".device-mount");
      if (!Comp || !mount) return;
      ReactDOM.createRoot(mount).render(
        <window.IPadFrame width={768} height={1024} theme="dark">
          <Comp />
        </window.IPadFrame>
      );
      fit(slot);
    });

    // re-fit after layout/fonts settle and on resize
    const refit = () => slots.forEach(fit);
    requestAnimationFrame(refit);
    setTimeout(refit, 120);
    setTimeout(refit, 400);
    if (document.fonts && document.fonts.ready) document.fonts.ready.then(refit);
    window.addEventListener("load", refit);
    let t;
    window.addEventListener("resize", () => { clearTimeout(t); t = setTimeout(refit, 80); }, { passive: true });
  }

  build();
})();
