class FSLightbox {
  #rootClass = "fsrd-lightbox";
  #element;
  #images = [];
  #currentIndex = 0;
  #modal;
  #modalInner;
  #modalToolbar;
  #modalCloseButton;
  #modalImage;
  #modalCaption;
  #modalCredit;
  #modalNavBar;
  #modalPagination;
  #modalNextButton;
  #modalPrevButton;
  #modalTabHandle;
  #modalActiveElement;
  #modalHiddenHandle;

  constructor(element) {
    this.#element = element;
    this.#init();
  }

  //#region Event Handlers

  handleImageClick = (e) => {
    e.preventDefault();
    let source = e.target;
    if (source.tagName === "A") {
      source = source.querySelector("img");
    }
    this.#showModal(source);
  };
/* 
  handleImageKeypress = (e) => {
    console.log("Image Keypress");
    if (e.key === "Enter") {
      console.log("Enter pressed");
      e.preventDefault();
      let source = e.target;
      let image = source.querySelector("img");
      this.#showModal(image);
    }
  };
 */
  handleCloseClick = (e) => {
    e.stopPropagation();
    this.#hideModal();
  }

  handleCloseKeypress = (e) => {
    e.stopPropagation();
    if (e.key === "Enter") {
      this.#hideModal();
    }
  }

  handleNextClick = (e) => {
    e.stopPropagation();
    this.#next();
  };

  handleNextKeypress = (e) => {
    e.stopPropagation();
    if (e.key === "Enter") {
      this.#next();
    }
  };

  handlePrevClick = (e) => {
    e.stopPropagation();
    this.#prev();
  };

  handlePrevKeypress = (e) => {
    e.stopPropagation();
    if (e.key === "Enter") {
      this.#prev();
    }
  };

  handleModalClick = (e) => {
    this.#hideModal();
  };

  handleModalKeypress = (e) => {
    console.log("Modal keypress");
    if (e.key === "Escape") {
      console.log("Escape pressed");
      this.#hideModal();
    }
  };

  //#endregion

  //#region Initialization

  #addModalClass(element, name) {
    element.classList.add(`${this.#rootClass}__modal__${name}`);
  }

  #buildModalElement(tagName, className) {
    let div = document.createElement(tagName);
    this.#addModalClass(div, className);
    return div;
  }

  #buildModal() {
    // Create the modal div.
    this.#modal = document.createElement("div");
    this.#modal.classList.add(`${this.#rootClass}__modal`);
    this.#modal.hidden = true;

    // Inner div of the modal.
    this.#modalInner = this.#buildModalElement("div", "inner");
    this.#modal.appendChild(this.#modalInner);

    //Modal Toolbar
    this.#modalToolbar = this.#buildModalElement("div", "toolbar");
    this.#modalInner.appendChild(this.#modalToolbar);
    this.#modalCloseButton = this.#buildModalElement("a", "close");
    this.#modalCloseButton.classList.add("usa-button");
    this.#modalCloseButton.setAttribute("tabindex", 0);
    this.#modalCloseButton.setAttribute("title", "Close");
    this.#modalCloseButton.innerHTML = "X";
    this.#modalCloseButton.addEventListener("click", this.handleCloseClick);
    this.#modalCloseButton.addEventListener("keypress", this.handleCloseKeypress);
    this.#modalToolbar.appendChild(this.#modalCloseButton);

    // Modal Image
    this.#modalImage = this.#buildModalElement("img", "img");
    this.#modalInner.appendChild(this.#modalImage);

    // Modal Caption
    this.#modalCaption = this.#buildModalElement("div", "caption");
    this.#modalCaption.hidden = true;
    this.#modalInner.appendChild(this.#modalCaption);

    // Modal Credit
    this.#modalCredit = this.#buildModalElement("div", "credit");
    this.#modalCredit.hidden = true;
    this.#modalInner.appendChild(this.#modalCredit);

    // Modal NavBar
    this.#modalNavBar = this.#buildModalElement("div", "navbar");
    this.#modalInner.appendChild(this.#modalNavBar);

    // Previous Button
    this.#modalPrevButton = this.#buildModalElement("a", "prev");
    this.#modalPrevButton.classList.add("usa-button");
    this.#modalPrevButton.setAttribute("tabindex", 0);
    this.#modalPrevButton.innerHTML = "◄ Prev";
    this.#modalPrevButton.addEventListener("click", this.handlePrevClick);
    this.#modalPrevButton.addEventListener("keypress", this.handlePrevKeypress);
    this.#modalNavBar.appendChild(this.#modalPrevButton);

    // Pagination
    this.#modalPagination = this.#buildModalElement("div", "pagination");
    this.#modalNavBar.appendChild(this.#modalPagination);

    // Next Button
    this.#modalNextButton = this.#buildModalElement("a", "next");
    this.#modalNextButton.classList.add("usa-button");
    this.#modalNextButton.setAttribute("tabindex", 0);
    this.#modalNextButton.innerHTML = "Next ▶";
    this.#modalNextButton.addEventListener("click", this.handleNextClick);
    this.#modalNextButton.addEventListener("keypress", this.handleNextKeypress);
    this.#modalNavBar.appendChild(this.#modalNextButton);

    this.#modal.addEventListener("click", this.handleModalClick);
    document.body.appendChild(this.#modal);
  }

  #init() {
    if (this.#element != null) {
      let elementImages = this.#element.querySelectorAll("img");
      elementImages.forEach((image) => {
        this.#images.push(image);

        let imageWrapper = document.createElement("a");
        imageWrapper.href = "#";
        image.parentNode.insertBefore(imageWrapper, image);
        imageWrapper.appendChild(image);

        imageWrapper.addEventListener("click", this.handleImageClick);
       // imageWrapper.addEventListener("keypress", this.handleImageKeypress);
        image.title = "Click to zoom";
      });

      this.#buildModal();
    }
  }

  //#endregion

  //#region Show/Hide

  #next() {
    if (this.#currentIndex < this.#images.length - 1) {
      this.#currentIndex = this.#currentIndex + 1;
    }
    this.#setModalImage();
  }

  #prev() {
    if (this.#currentIndex > 0) {
      this.#currentIndex = this.#currentIndex - 1;
    }
    this.#setModalImage();
  }

  #setCurrentIndex(image) {
    this.#currentIndex = this.#images.indexOf(image);
  }

  #setModalImage() {
    let image = this.#images[this.#currentIndex];
    this.#modalImage.src = image.src;
    this.#modalImage.alt = image.alt;

    if (image.hasAttribute("data-caption")) {
      this.#modalCaption.innerHTML = image
        .getAttribute("data-caption")
        .replaceAll(""", '"');
      this.#modalCaption.hidden = false;
    } else {
      this.#modalCaption.hidden = true;
    }

    if (image.hasAttribute("data-credit")) {
      this.#modalCredit.innerHTML = image.getAttribute("data-credit");
      this.#modalCredit.hidden = false;
    } else {
      this.#modalCredit.hidden = true;
    }

    this.#modalPagination.innerText = `${this.#currentIndex + 1} / ${
      this.#images.length
    }`;

    if (this.#currentIndex === 0) {
      this.#modalPrevButton.classList.add("disabled");
    } else {
      this.#modalPrevButton.classList.remove("disabled");
    }

    if (this.#currentIndex === this.#images.length - 1) {
      this.#modalNextButton.classList.add("disabled");
    } else {
      this.#modalNextButton.classList.remove("disabled");
    }
  }

  #showModal(image) {
    this.#modalActiveElement = document.activeElement;
    this.#modalTabHandle = ally.maintain.tabFocus({
      context: this.#modal
    });
    this.#modalHiddenHandle = ally.maintain.hidden({
      filter: this.#modal
    })
    this.#setCurrentIndex(image);
    this.#setModalImage();

    this.#modal.hidden = false;
  }

  #hideModal() {
    this.#modal.hidden = true;
    this.#modalTabHandle.disengage();
    this.#modalHiddenHandle.disengage();
    this.#modalActiveElement.focus();
    this.#modal.hidden = true;
  }

  //#endregion
}

let lightboxDivs = document.querySelectorAll('.fsrd-lightbox'); 
lightboxDivs.forEach(lightboxDiv => {
  let fsLightbox = new FSLightbox(lightboxDiv);
});