(function () {
  let lastTrigger = null;

  function ensureLightbox() {
    let overlay = document.getElementById("tutorialImageLightbox");
    if (overlay) return overlay;

    overlay = document.createElement("div");
    overlay.id = "tutorialImageLightbox";
    overlay.className = "tutorial-image-lightbox";
    overlay.hidden = true;
    overlay.innerHTML = [
      '<div class="tutorial-image-lightbox-backdrop" data-image-lightbox-close="true"></div>',
      '<div class="tutorial-image-lightbox-panel" role="dialog" aria-modal="true" aria-labelledby="tutorialImageLightboxTitle">',
      '  <div class="tutorial-image-lightbox-header">',
      '    <div id="tutorialImageLightboxTitle" class="tutorial-image-lightbox-title"></div>',
      '    <button class="tutorial-image-lightbox-close" type="button" data-image-lightbox-close="true" aria-label="Close full-size image">&times;</button>',
      '  </div>',
      '  <div class="tutorial-image-lightbox-viewport">',
      '    <img class="tutorial-image-lightbox-image" alt="" />',
      '  </div>',
      '</div>'
    ].join("");

    overlay.addEventListener("click", (event) => {
      if (event.target instanceof Element && event.target.dataset.imageLightboxClose === "true") {
        closeLightbox();
      }
    });
    document.body.appendChild(overlay);
    return overlay;
  }

  function openLightbox(trigger) {
    const sourceImage = trigger.querySelector("img");
    if (!sourceImage) return;

    const overlay = ensureLightbox();
    const image = overlay.querySelector(".tutorial-image-lightbox-image");
    const title = overlay.querySelector(".tutorial-image-lightbox-title");
    const closeButton = overlay.querySelector(".tutorial-image-lightbox-close");
    if (!image || !title || !closeButton) return;

    lastTrigger = trigger;
    image.src = sourceImage.currentSrc || sourceImage.src;
    image.alt = sourceImage.alt;
    title.textContent = trigger.dataset.imageCaption || sourceImage.alt || "Full-size image";
    overlay.hidden = false;
    document.body.classList.add("tutorial-image-lightbox-open");
    closeButton.focus();
  }

  function closeLightbox() {
    const overlay = document.getElementById("tutorialImageLightbox");
    if (!overlay || overlay.hidden) return;
    overlay.hidden = true;
    document.body.classList.remove("tutorial-image-lightbox-open");
    if (lastTrigger) lastTrigger.focus();
    lastTrigger = null;
  }

  function run() {
    document.querySelectorAll("[data-image-lightbox]").forEach((trigger) => {
      trigger.addEventListener("click", () => openLightbox(trigger));
    });
  }

  document.addEventListener("keydown", (event) => {
    if (event.key === "Escape") closeLightbox();
  });

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