if (!LFP) {
  error("LFP not loaded: image_collage");
}
if (!LFP.MODULES.COLLAGE) {
  LFP.MODULES.COLLAGE = new Object();
  LFP.MODULES.COLLAGE.init = function () {
    (async () => {
      while (typeof PhotoSwipe === "undefined") {
        console.log("Waiting for PhotoSwipe...");
        await new Promise((resolve) => setTimeout(resolve, 260));
      }
      console.log("About to initialize collages >>");
      LFP.MODULES.COLLAGE.initPhotoSwipeFromDOM(".collage.unprocessed");
    })();
  };
  LFP.MODULES.COLLAGE.parseThumbnailElements = function (el) {
    let thumbElements = el.childNodes,
      numNodes = thumbElements.length,
      items = [],
      figureEl,
      linkEl,
      childElements,
      size,
      item;

    for (var i = 0; i < numNodes; i++) {
      figureEl = thumbElements[i]; // <figure> element
      // include only element nodes
      if (figureEl.nodeType !== 1) {continue;}

      linkEl = figureEl.children[0]; // <a> element

      size = linkEl.getAttribute("data-size").split("x");

      // create slide object
      item = {
        src: linkEl.getAttribute("href"),
        w: parseInt(size[0], 10),
        h: parseInt(size[1], 10),
        author: linkEl.getAttribute("data-author"),
      };

      if (figureEl.children.length > 1) {
        // <figcaption> content
        item.title = figureEl.children[1].innerHTML;
      }

      if (linkEl.children.length > 0) {
        // <img> thumbnail element, retrieving thumbnail url
        item.msrc = linkEl.children[0].getAttribute("src");
      }

      item.el = figureEl; // save link to element for getThumbBoundsFn
      items.push(item);
    }

    return items;
  };
  LFP.MODULES.COLLAGE.closest = function closest(el, fn) {
    // find nearest parent element
    return el && (fn(el) ? el : closest(el.parentNode, fn));
  };
  LFP.MODULES.COLLAGE.onThumbnailsClick = function (e) {
    console.log("LFP.MODULES.COLLAGE.onThumbnailsClick >>> ");
    // triggers when user clicks on thumbnail
    e = e || window.event;
    e.preventDefault ? e.preventDefault() : (e.returnValue = false);

    let eTarget = e.target || e.srcElement;

    // find root element of slide
    let clickedListItem = LFP.MODULES.COLLAGE.closest(eTarget, function (el) {
      return el.tagName && el.tagName.toUpperCase() === "FIGURE";
    });

    if (!clickedListItem) {return;}

    // find index of clicked item by looping through all child nodes
    // alternatively, you may define index via data- attribute
    let clickedGallery = clickedListItem.parentNode,
      childNodes = clickedListItem.parentNode.childNodes,
      numChildNodes = childNodes.length,
      nodeIndex = 0,
      index;

    for (var i = 0; i < numChildNodes; i++) {
      if (childNodes[i].nodeType !== 1) {continue;}

      if (childNodes[i] === clickedListItem) {
        index = nodeIndex;
        break;
      }
      nodeIndex++;
    }

    // open PhotoSwipe if valid index found
    if (index >= 0) {
      LFP.MODULES.COLLAGE.openPhotoSwipe(index, clickedGallery);
    }
    return false;
  };
  LFP.MODULES.COLLAGE.photoswipeParseHash = function () {
    // parse picture index and gallery index from URL (#&pid=1&gid=2)
    let hash = window.location.hash.substring(1),
      params = {};

    if (hash.length < 5) {
      return params;
    }
    let vars = hash.split("&");
    for (var i = 0; i < vars.length; i++) {
      if (!vars[i]) {continue;}
      let pair = vars[i].split("=");
      if (pair.length < 2) {continue;}
      params[pair[0]] = pair[1];
    }

    if (params.gid) {
      params.gid = parseInt(params.gid, 10);
    }

    return params;
  };
  LFP.MODULES.COLLAGE.openPhotoSwipe = function (
    index,
    galleryElement,
    disableAnimation,
    fromURL
  ) {
    console.log("LFP.MODULES.COLLAGE.openPhotoSwipe >>> ");
    let pswpElement = document.querySelectorAll(".pswp")[0],
      gallery,
      options,
      items;

    items = LFP.MODULES.COLLAGE.parseThumbnailElements(galleryElement);

    //trap the focus inside whatever gallery has been opened
    let focusableEls = pswpElement.querySelectorAll(
      'a[href]:not([disabled]), button:not([disabled]), textarea:not([disabled]), input[type="text"]:not([disabled]), input[type="radio"]:not([disabled]), input[type="checkbox"]:not([disabled]), select:not([disabled])'
    );

    console.log(focusableEls);
    let firstFocusableEl = focusableEls[0];
    let lastFocusableEl = focusableEls[focusableEls.length - 1];
    let KEYCODE_TAB = 9;

    pswpElement.addEventListener("keydown", function (e) {
      if (e.key === "Tab" || e.keyCode === KEYCODE_TAB) {
        if (e.shiftKey) {
          /* shift + tab */ if (document.activeElement === firstFocusableEl) {
            lastFocusableEl.focus();
            e.preventDefault();
          }
        } /* tab */ else {
          if (document.activeElement === lastFocusableEl) {
            firstFocusableEl.focus();
            e.preventDefault();
          }
        }
      }
    });

    // define options (if needed)
    options = {
      //turn off zooming of gallery images
      maxSpreadZoom: 1,
      getDoubleTapZoom: function (isMouseClick, item) {
        return item.initialZoomLevel;
      },
      // UI options
      zoomEl: false,
      bgOpacity: 0.9,
      // define gallery index (for URL)
      galleryUID: galleryElement.getAttribute("data-pswp-uid"),
      getThumbBoundsFn: function (index) {
        // See Options -> getThumbBoundsFn section of documentation for more info
        let thumbnail = items[index].el.getElementsByTagName("img")[0], // find thumbnail
          pageYScroll =
            window.pageYOffset || document.documentElement.scrollTop,
          rect = thumbnail.getBoundingClientRect();
        return { x: rect.left, y: rect.top + pageYScroll, w: rect.width };
      },
      addCaptionHTMLFn: function (item, captionEl, isFake) {
        if (!item.title) {
          captionEl.children[0].innerText = "";
          return false;
        }
        // CHECK IF PHOTO CREDIT EXISTS BEFORE ADDING LABEL
        let creditString = "";
        if (item.author != "") {
          creditString =
            '<span class="collage-photo-credit"> (' +
            item.author +
            ")</span>";
        }
        captionEl.children[0].innerHTML =
          '<span class="collage-photo-caption">' +
          item.title +
          "</span>" +
          creditString;
        return true;
      },
    };

    // PhotoSwipe opened from URL
    if (fromURL) {
      if (options.galleryPIDs) {
        // parse real index when custom PIDs are used
        // http://photoswipe.com/documentation/faq.html#custom-pid-in-url
        for (var j = 0; j < items.length; j++) {
          if (items[j].pid == index) {
            options.index = j;
            break;
          }
        }
      } else {
        // in URL indexes start from 1
        options.index = parseInt(index, 10) - 1;
      }
    } else {
      options.index = parseInt(index, 10);
    }

    // exit if index not found
    if (isNaN(options.index)) {return;}

    if (disableAnimation) {
      options.showAnimationDuration = 0;
    }

    // Pass data to PhotoSwipe and initialize it
    gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
    gallery.init();
  };
  LFP.MODULES.COLLAGE.initPhotoSwipeFromDOM = function (gallerySelector) {
    // loop through all gallery elements and bind events
    let galleryElements = document.querySelectorAll(gallerySelector);
    console.log("GALLERIES [" + gallerySelector + "]");
    console.log(galleryElements);
    LFP.MODULES.COLLAGE.setupPhotoCollages(galleryElements);

    // Parse URL and open gallery if it contains #&pid=3&gid=1
    let hashData = LFP.MODULES.COLLAGE.photoswipeParseHash();
    if (hashData.pid && hashData.gid) {
      LFP.MODULES.COLLAGE.openPhotoSwipe(
        hashData.pid,
        galleryElements[hashData.gid - 1],
        true,
        true
      );
    }
  };
  LFP.MODULES.COLLAGE.initPhotoSwipeFromId = function (gallerySelector) {
    console.log("GALLERY [" + gallerySelector + "]");
    let gallery = document.querySelector(gallerySelector);

    LFP.MODULES.COLLAGE.buildCollage(gallery);

    console.log(
      `setting event listener for: ${gallery.getAttribute(
        "data-collage-index"
      )}`
    );
    console.log(gallery);
    gallery.addEventListener("click", LFP.MODULES.COLLAGE.onThumbnailsClick);
    gallery.classList.remove("unprocessed");
    console.log(gallery);

    // Parse URL and open gallery if it contains #&pid=3&gid=1
    let hashData = LFP.MODULES.COLLAGE.photoswipeParseHash();
    if (hashData.pid && hashData.gid) {
      LFP.MODULES.COLLAGE.openPhotoSwipe(
        hashData.pid,
        galleryElements[hashData.gid - 1],
        true,
        true
      );
    }
  };

  LFP.MODULES.COLLAGE.setupPhotoCollages = function (collageElements) {
    for (var c = 0; c < collageElements.length; c++) {
      let collage = collageElements[c];
      let collageIndex = collage.getAttribute("data-collage-index");
      LFP.MODULES.COLLAGE.buildCollage(collage);

      console.log("setting event listener for:");
      console.log(collage);
      collage.addEventListener("click", LFP.MODULES.COLLAGE.onThumbnailsClick);
      collage.classList.remove("unprocessed");
      console.log(collage);
    }
  };
  LFP.MODULES.COLLAGE.buildCollage = function (currentCollage) {
    let dataSizePortrait = "1435x1600";
    let dataSizeLandscape = "1665x900";
    let dataSizeThreeByTwo = "1665x1110";
    let dataSizeSquare = "1435x1435";

    let srcArray = null;
    let sizeArray = null;
    let collageName = currentCollage.getAttribute("data-count");
    let collageIndex = currentCollage.getAttribute("data-collage-index");
    let collageType = currentCollage.getAttribute("data-collage-type");
    let portraitSize = currentCollage.getAttribute("data-size-portrait");
    let landscapeSize = currentCollage.getAttribute("data-size-landscape");
    let threeByTwoSize = currentCollage.getAttribute("data-size-threeByTwo");
    let squareSize = currentCollage.getAttribute("data-size-square");
    let singleSize = currentCollage.getAttribute("data-size-single");

    console.log(
      `PROCESSING AN IMAGE GALLERY [${collageIndex}]: ${collageType}`
    );

    switch (collageType) {
      case "single":
        srcArray = ["data-src"];
        sizeArray = [singleSize];
        break;
      case "fourGallery":
        currentCollage.classList.add("fourGallery");
        srcArray = [
          "data-src-landscape",
          "data-src-portrait",
          "data-src-portrait",
          "data-src-landscape",
        ];
        sizeArray = [
          dataSizeLandscape,
          dataSizePortrait,
          dataSizePortrait,
          dataSizeLandscape,
        ];
        break;
      case "fourGalleryFlip":
        currentCollage.classList.add("fourGallery", "flip");
        srcArray = [
          "data-src-portrait",
          "data-src-landscape",
          "data-src-landscape",
          "data-src-portrait",
        ];
        sizeArray = [
          dataSizePortrait,
          dataSizeLandscape,
          dataSizeLandscape,
          dataSizePortrait,
        ];
        break;
      case "fourGalleryThreeByTwo":
        currentCollage.classList.add("fourGallery", "landscape32");
        srcArray = [
          "data-src-threeByTwo",
          "data-src-threeByTwo",
          "data-src-threeByTwo",
          "data-src-threeByTwo",
        ];
        sizeArray = [
          dataSizeThreeByTwo,
          dataSizeThreeByTwo,
          dataSizeThreeByTwo,
          dataSizeThreeByTwo,
        ];
        break;
      case "fourGallerySquare":
        currentCollage.classList.add("fourGallerySquare");
        srcArray = [
          "data-src-square",
          "data-src-square",
          "data-src-square",
          "data-src-square",
        ];
        sizeArray = [
          dataSizeSquare,
          dataSizeSquare,
          dataSizeSquare,
          dataSizeSquare,
        ];
        break;
      case "fiveGallery":
        currentCollage.classList.add("fiveGallery");
        srcArray = [
          "data-src-landscape",
          "data-src-landscape",
          "data-src-landscape",
          "data-src-landscape",
          "data-src-portrait",
        ];
        sizeArray = [
          dataSizeLandscape,
          dataSizeLandscape,
          dataSizeLandscape,
          dataSizeLandscape,
          dataSizePortrait,
        ];
        break;
      case "fiveGalleryFlip":
        currentCollage.classList.add("fiveGallery", "flip");
        srcArray = [
          "data-src-landscape",
          "data-src-landscape",
          "data-src-portrait",
          "data-src-landscape",
          "data-src-landscape",
        ];
        sizeArray = [
          dataSizeLandscape,
          dataSizeLandscape,
          dataSizePortrait,
          dataSizeLandscape,
          dataSizeLandscape,
        ];
        break;
      default:
        srcArray = null;
        sizeArray = null;
        break;
    }
    if (srcArray != null && sizeArray != null) {
      let figures = currentCollage.querySelectorAll("figure");
      for (var i = 0; i < figures.length; i++) {
        let currentImage = figures[i];
        var imgID = `${collageIndex}img${i}`;
        console.log(`  IMAGE ${imgID}`);
        if (i == 0) {currentImage.classList.add("collage-anchor");}
        let imageHREF = currentImage.getAttribute(srcArray[i]);
        let imageLink = currentImage.querySelector("a");
        imageLink.setAttribute("href", imageHREF);
        imageLink.setAttribute("data-size", sizeArray[i]);
        imageLink.setAttribute("id", imgID);
        imageLink.querySelector("img").setAttribute("src", imageHREF);
      }
    }
    currentCollage.setAttribute("data-pswp-uid", collageIndex);
    currentCollage.id = collageIndex;
  };

  LFP.MODULES.COLLAGE.init();
}
