import PhotoSwipeLightbox from 'photoswipe/lightbox';

const imgCache = new Map(); // Cache pro zapamatování rozměrů

const options = {
   bgOpacity: 1,
   loop: false,
   pinchToClose: false,
   closeOnVerticalDrag: false,
   showAnimationDuration: 0,
   hideAnimationDuration: 0,
   clickToCloseNonZoomable: false,
   zoom: true,
   pswpModule: () => import('photoswipe'),
   arrowPrevSVG: require('@assets/icons/caret-left.svg?raw'),
   arrowNextSVG: require('@assets/icons/caret-right.svg?raw'),
   closeSVG: require('@assets/icons/close.svg?raw'),
   counter: true,
}

const lightbox = new PhotoSwipeLightbox({
   gallery: '[data-gallery-wrapper], .w-figure a[data-rel="gallery"][rel="gallery"]',
   children: 'a[data-rel="gallery"]',
   ...options,
   paddingFn: (viewportSize, itemData, index) => {
      return {
         top: 0,
         bottom: viewportSize.x < 768 ? (viewportSize.x < 544 ? 50 : 64) : 0,
         left: viewportSize.x < 768 ? 20 : (viewportSize.x < 1200 ? 50 : 100),
         right: viewportSize.x < 768 ? 20 : 50
      };
   }
});

const lightbox_single = new PhotoSwipeLightbox({
   gallery: '.w-figure a[data-rel="gallery"][rel="gallery"]',
   ...options,
   padding: { top: 0, bottom: 0, left: 20, right: 20 },
});

const lightboxes = [lightbox, lightbox_single];

lightbox.addFilter('itemData', (itemData, index) => {
   const thumbUrl = itemData.element.dataset.pswpThumb;
   if (thumbUrl) {
      itemData.thumbUrl = thumbUrl;
   }
   return itemData;
});

lightbox.on('uiRegister', function() {
   lightbox.pswp.ui.registerElement({
      name: 'thumbsIndicator',
      className: 'pswp__thumbs-indicator',
      appendTo: 'root',
      onInit: (el, pswp) => {
         const thumbs: HTMLElement[] = [];
         let thumb;
         let thumb_img;
         let prevIndex = -1;

         for (let i = 0; i < pswp.getNumItems(); i++) {
            thumb_img = document.createElement('img');
            thumb_img.src = pswp.getItemData(i).thumbUrl ?? pswp.getItemData(i).src;
            thumb = document.createElement('picture');
            thumb.append(thumb_img);
            thumb.className = 'pswp__thumb';
            thumb.onclick = (e) => {
               pswp.goTo(i);
            };
            el.appendChild(thumb);
            thumbs.push(thumb);
         }

         pswp.on('change', (a) => {
            if (prevIndex >= 0) {
               thumbs[prevIndex].classList.remove('pswp__thumb--active');
            }
            thumbs[pswp.currIndex].classList.add('pswp__thumb--active');
            prevIndex = pswp.currIndex;
         });
      }
   });
});

lightbox.on("afterInit", () => {
   document.querySelector(".pswp").addEventListener("wheel", (e) => {
      ["pswp__thumbs-indicator"].forEach(className => {
         if ((e.target as HTMLElement).classList.contains(className) || (e.target as HTMLElement).closest(`.${className}`)) {
            e.stopPropagation();
         }
      });
   }, { capture: true, passive: true });
});

lightboxes.forEach(lb => lb.on('contentLoad', (e) => {
   const { content } = e;
   if (content.type === 'video') {
      // prevent the deafult behavior
      e.preventDefault();

      // Create a container for iframe
      // and assign it to the `content.element` property
      content.element = document.createElement('div');
      content.element.className = 'pswp__video-container';

      const iframe = document.createElement('iframe');
      iframe.setAttribute('allowfullscreen', '');
      iframe.src = content.data.src;
      content.element.appendChild(iframe);
   }
}));

lightboxes.forEach(lb => lb.on('beforeOpen', (e) => {
   document.body.classList.add('modal-opened');
   window.history.pushState( { 'photoswipe': true } , '', new URL(window.location.href) + '#ui-state=dialog');
}));

lightboxes.forEach(lb => lb.on('destroy', () => {
   document.body.classList.remove('modal-opened');
   if (window.location.hash.includes('#ui-state=dialog')) {
      history.back();
   }
   imgCache.clear();
}));

let isRefreshing = false;
lightboxes.forEach(lb => lb.on('contentActivate', (e) => {
   const slide = e.content.slide;
   if (!slide) {
      return;
   }

   if (imgCache.has(slide.data.src)) {
      const { width, height } = imgCache.get(slide.data.src);
      slide.data.w = width;
      slide.data.h = height;
      slide.width = width;
      slide.height = height;

      lb.pswp.updateSize(true)
   }
}));

lightboxes.forEach(lb => lb.on('gettingData', (e) => {
   const slide = e.slide;
   if (!slide) {
      return;
   }

   if (!imgCache.has(slide.data.src)) {
      const img = new Image();
      img.src = slide.data.src;
      img.onload = function () {
         slide.data.w = img.naturalWidth;
         slide.data.h = img.naturalWidth;
         slide.width = img.naturalWidth;
         slide.height = img.naturalHeight;

         imgCache.set(slide.data.src, { width: slide.width, height: slide.height });
         lb.pswp.updateSize(true);
      };
   }
}));

lightboxes.forEach(lb => lb.init());
window.wpjLightbox = lightbox;
window.onhashchange = function() {
   lightboxes.forEach(lb => {
      if (lb?.pswp?.isOpen) {
         lb?.pswp?.close();
      }
   })
}
