import { Controller } from "@hotwired/stimulus"
import PhotoSwipeLightbox from 'photoswipe/lightbox'
import PhotoSwipe from 'photoswipe'
import 'photoswipe/dist/photoswipe.css'

export default class extends Controller {
    static targets = ['image', 'gallery']

    connect() {
        this.initPhotoSwipeLightbox()
    }

    initPhotoSwipeLightbox() {
        const lightbox = new PhotoSwipeLightbox({
            gallery: this.galleryTarget,
            children: 'a',
            pswpModule: PhotoSwipe,
            initialZoomInEndEvent: 'mousedown',
            dataSource: (items) => {
                return items.map((item) => ({
                    src: item.dataset.pswpSrc,
                    w: parseInt(item.dataset.pswpWidth, 10),
                    h: parseInt(item.dataset.pswpHeight, 10),
                    title: item.dataset.pswpCaption,
                }))
            },
            padding: { top: 0, bottom: 0, left: 0, right: 0 }, // 自定义图片与页面边界的填充
            closeOnScroll: false,
            zoom: true, // 启用缩放功能
            bgOpacity: 0.9, // 背景透明度
            pswpUIOptions: {
                arrowPrev: true,
                arrowNext: true,
                zoom: true,     // 添加缩放按钮
                fullscreen: true, // 添加全屏按钮
                counter: true,    // 显示当前图片编号
            }
        })
        lightbox.init()
        // console.log('PhotoSwipeLightbox instance:', lightbox);
    }
}