<script>
import PhotoSwipeLightbox from 'photoswipe/lightbox'
import 'photoswipe/style.css'

let lightbox: PhotoSwipeLightbox
const pswp = import('photoswipe')

function setupPhotoSwipe() {
  const bodyElement = document.body
  if (!bodyElement.hasAttribute('data-photoswipe-initialized')) {
    lightbox = new PhotoSwipeLightbox({
      gallery: 'article.heti img',
      pswpModule: () => pswp,
      bgOpacity: 0.9,
      padding: {
        top: window.innerHeight * 0.1,
        bottom: window.innerHeight * 0.1,
        left: window.innerWidth * 0.073,
        right: window.innerWidth * 0.073,
      },
      zoom: false,
      close: false,
      wheelToZoom: true,
      imageClickAction: 'close',
      tapAction: 'close',
    })

    // Set image dimensions
    lightbox.addFilter('domItemData', (itemData, element) => {
      if (element instanceof HTMLImageElement) {
        // Set image source
        itemData.src = element.src

        // Set dimensions with fallback to window size
        itemData.w = Number(element.naturalWidth || window.innerWidth)
        itemData.h = Number(element.naturalHeight || window.innerHeight)

        // Set thumbnail source
        itemData.msrc = element.src
      }
      return itemData
    })

    lightbox.init()

    bodyElement.setAttribute('data-photoswipe-initialized', 'true')
  }
}

setupPhotoSwipe()
document.addEventListener('astro:page-load', setupPhotoSwipe)
</script>

<style is:global>
.pswp .pswp__bg {
  --at-apply: 'bg-background!'
}
</style>
