let tmpImage = new Image();
tmpImage.src = $("#myImage").attr("src");

tmpImage.onload = function () {
  // Get original Image Dimensions
  $("body").append(tmpImage);
  imageWidth = $(tmpImage).width();
  imageHeight = $(tmpImage).height();
  imageAspect = imageWidth / imageHeight;

  $(tmpImage).remove();
};

// -------------- Zoom in & Zoom out Image -------------
let isToggled = false; // initial state (zoomed-out)

// Change the size of the image
function updateImageSize() {
  $("#myImage").css({
    width: isToggled ? imageWidth / 2 : (!isPortrait ? "auto" : "100%"),
    height: isToggled ? imageHeight / 2 : "100%",
    cursor: isToggled ? "zoom-out" : "zoom-in",
  });
}
// Toggle the state
$("#myImage").click(function (e) {
  if (!isToggled) {
    const rect = this.getBoundingClientRect();

    let displayWidth = rect.width;
    let displayHeight = rect.height;

    if (displayHeight * imageAspect < displayWidth) {
      displayWidth = displayHeight * imageAspect;
    } else {
      displayHeight = displayWidth / imageAspect;
    }

    const offsetX = (rect.width - displayWidth) / 2;
    const offsetY = (rect.height - displayHeight) / 2;

    // Clicked position inside the displayed image clamped to image bounds
    const clickedX = (e.clientX - rect.left - offsetX) / displayWidth;
    const clickedY = (e.clientY - rect.top - offsetY) / displayHeight;

    // For fixing final position based on treshold to move near edges.
    const SNAP_THRESHOLD = 0.1; // 10%

    let x = clickedX;
    let y = clickedY;

    if (x < SNAP_THRESHOLD) x = 0;
    else if (x > 1 - SNAP_THRESHOLD) x = 1;

    if (y < SNAP_THRESHOLD) y = 0;
    else if (y > 1 - SNAP_THRESHOLD) y = 1;

    isToggled = !isToggled;
    updateImageSize();

    requestAnimationFrame(() => {
      const scrollContainer = $("#inner_container");

      const viewportWidth = scrollContainer[0].clientWidth;
      const viewportHeight = scrollContainer[0].clientHeight;
      const maxScrollX = scrollContainer[0].scrollWidth - viewportWidth;
      const maxScrollY = scrollContainer[0].scrollHeight - viewportHeight;

      // Set scroll values and make the scroll
      const scrollX = maxScrollX * x;
      const scrollY = maxScrollY * y;
      scrollContainer.scrollLeft(scrollX);
      scrollContainer.scrollTop(scrollY);
    });
  } else {
    isToggled = !isToggled;
    updateImageSize();
  }
});