(function () {
  const DESIGN_W = 1920;
  const DESIGN_H = 1080;
  const MIN_WIDTH = 1280;

  if (window.__osakaViewportScale) return;
  window.__osakaViewportScale = true;

  const OVERLAY_ID = "viewport-too-small";
  const SHELL_ID = "viewport-shell";
  const CANVAS_ID = "viewport-canvas";

  function createOverlay() {
    const el = document.createElement("div");
    el.id = OVERLAY_ID;
    el.className = "viewport-too-small";
    el.hidden = true;
    el.setAttribute("role", "alertdialog");
    el.setAttribute("aria-modal", "true");
    el.setAttribute("aria-labelledby", "viewport-too-small-title");
    el.innerHTML =
      '<div class="viewport-too-small__panel">' +
      '<p class="viewport-too-small__kicker">Osaka SCORM</p>' +
      '<h2 id="viewport-too-small-title">Schermo troppo stretto</h2>' +
      "<p>Questo percorso è pensato per <strong>desktop</strong>. Apri il corso con una finestra larga almeno <strong>1280px</strong> (monitor o laptop a schermo intero).</p>" +
      '<p class="viewport-too-small__hint">Layout di progetto: 1920×1080, scalato per adattarsi al tuo schermo.</p>' +
      "</div>";
    return el;
  }

  function mount() {
    document.documentElement.classList.add("viewport-fixed");

    let overlay = document.getElementById(OVERLAY_ID);
    if (!overlay) {
      overlay = createOverlay();
      document.body.prepend(overlay);
    }

    let shell = document.getElementById(SHELL_ID);
    let canvas = document.getElementById(CANVAS_ID);

    if (!shell) {
      shell = document.createElement("div");
      shell.id = SHELL_ID;
      shell.className = "viewport-shell";

      canvas = document.createElement("div");
      canvas.id = CANVAS_ID;
      canvas.className = "viewport-canvas";

      const nodes = [...document.body.children].filter(
        (node) => node.id !== OVERLAY_ID
      );
      nodes.forEach((node) => canvas.appendChild(node));

      shell.appendChild(canvas);
      document.body.appendChild(shell);
    } else {
      canvas = document.getElementById(CANVAS_ID);
    }

    function layout() {
      const vw = window.innerWidth;
      const vh = window.innerHeight;
      const blocked = vw < MIN_WIDTH;

      document.documentElement.classList.toggle("viewport-blocked", blocked);
      overlay.hidden = !blocked;

      if (blocked || !canvas) {
        return;
      }

      const scale = Math.min(vw / DESIGN_W, vh / DESIGN_H);
      canvas.style.width = DESIGN_W + "px";
      canvas.style.height = DESIGN_H + "px";
      canvas.style.transform = "scale(" + scale + ")";
      shell.dataset.scale = String(Math.round(scale * 1000) / 1000);
    }

    layout();
    window.addEventListener("resize", layout, { passive: true });
    window.addEventListener("orientationchange", layout);
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", mount);
  } else {
    mount();
  }
})();
