// ============================================================
// bedside/image-lightbox.js
// IMAGE LIGHTBOX — any element with data-img-src opens fullscreen.
// ============================================================

export function init() {
  document.addEventListener('click', function(e) {
    var opener = e.target.closest && e.target.closest('[data-img-src]');
    if (opener) {
      e.preventDefault();
      var lb = document.getElementById('img-lightbox');
      if (!lb) return;
      var src = opener.dataset.imgSrc;
      var title = opener.dataset.imgTitle || '';
      document.getElementById('img-lightbox-img').src = src;
      document.getElementById('img-lightbox-img').alt = title;
      document.getElementById('img-lightbox-title').textContent = title;
      document.getElementById('img-lightbox-open').href = src;
      lb.style.display = 'flex';
      return;
    }
    // Close on close button, on backdrop click (not on image), and on Escape (below)
    var closeBtn = e.target.closest && e.target.closest('#img-lightbox-close');
    var lb2 = document.getElementById('img-lightbox');
    if (!lb2 || lb2.style.display !== 'flex') return;
    if (closeBtn || e.target === lb2) {
      lb2.style.display = 'none';
      document.getElementById('img-lightbox-img').src = '';
    }
  });
  document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
      var lb = document.getElementById('img-lightbox');
      if (lb && lb.style.display === 'flex') {
        lb.style.display = 'none';
        document.getElementById('img-lightbox-img').src = '';
      }
    }
  });
}
