/**
 * Product Gallery: Swiper + GLightbox + Variation Handler
 * Optimized Version — Fast, Stable, ES5 Compatible
 * @version 3.1.0 - Fixed GLightbox variation sync
 */
(function ($) {
  "use strict";

  // Global instances
  var lightbox = null;
  var swiperProductGalleryDisplay = null;

 // ----------------------------------------------------
  // SWIPER GALLERY INIT
  // ----------------------------------------------------
  function ProductGallerySwiperInit() {
    const gallery = document.querySelector(".js-product-gallery");

    if (!gallery) return;

    const main = gallery.querySelector(".rt-swiper-gallery__featured .swiper");
    const thumbnail = gallery.querySelector(".rt-swiper-gallery__thumbnails .swiper");

    if (!main || !thumbnail) return;

    // Navigation
    const sliderNavigation = new Swiper(thumbnail, {
      spaceBetween: 10,
      slidesPerView: 5,
      navigation: {
        nextEl: thumbnail.querySelector(".swiper-button-next"),
        prevEl: thumbnail.querySelector(".swiper-button-prev"),
      },
      breakpoints: {
        768: {
          slidesPerView: 7,
        },
      },
      watchSlidesProgress: true,
      freeMode: true,
    });

    // Main
    const sliderMain = new Swiper(main, {
      spaceBetween: 10,
      slidesPerView: 1,
      autoHeight: true,
      navigation: {
        nextEl: main.querySelector(".swiper-button-next"),
        prevEl: main.querySelector(".swiper-button-prev"),
      },
      pagination: {
        el: main.querySelector(".swiper-pagination"),
        type: "fraction",
      },
      thumbs: {
        swiper: sliderNavigation,
      },
      watchSlidesProgress: true,
      freeMode: false,
    });

    // Store instance
    swiperProductGalleryDisplay = sliderMain;
  }
  document.addEventListener("DOMContentLoaded", ProductGallerySwiperInit);

  // ----------------------------------------------------
  // GLIGHTBOX INIT (DESTROY & RECREATE)
  // ----------------------------------------------------
  function ProductGalleryGLightboxInit() {
    // Destroy existing instance
    if (lightbox) {
      lightbox.destroy();
      lightbox = null;
    }

    // Create new instance
    lightbox = GLightbox({
      selector: ".js-glightbox",
      touchNavigation: true,
      loop: true,
    });

    lightbox.on("open", () => {
      const container = document.querySelector(".glightbox-container");
      if (container) container.classList.add("rt-glightbox");
    });
  }
  document.addEventListener("DOMContentLoaded", ProductGalleryGLightboxInit);

  // ----------------------------------------------------
  // VARIATION IMAGE HANDLER
  // ----------------------------------------------------
  $(function () {
    var $form = $("form.variations_form");

    if (!$form.length) return;

    var selectors = {
      featuredImage: "#rt_product_gallery .rt-swiper-gallery__featured .swiper-slide.is-featured-image img",
      thumbnailImage: "#rt_product_gallery  .rt-swiper-gallery__thumbnails .swiper-slide:first img",
      featuredLink: "#rt_product_gallery .rt-swiper-gallery__featured .swiper-slide.is-featured-image a",
    };

    var state = {
      originalData: {
        featured: {},
        thumbnail: {},
      },
    };

    /* Save Original */
    function initOriginalData() {
      var featuredImg = $(selectors.featuredImage).first();
      var featuredLink = featuredImg.closest("a");

      if (featuredImg.length) {
        state.originalData.featured = {
          src: featuredImg.attr("src") || "",
          srcset: featuredImg.attr("srcset") || "",
          sizes: featuredImg.attr("sizes") || "",
          href: featuredLink.attr("href") || "",
        };
      }

      var thumbImg = $(selectors.thumbnailImage).first();
      if (thumbImg.length) {
        state.originalData.thumbnail = {
          src: thumbImg.attr("src") || "",
          srcset: thumbImg.attr("srcset") || "",
          sizes: thumbImg.attr("sizes") || "",
        };
      }
    }

    /* Save temporary */
    function saveOriginalToData(img, link) {
      if (img.length && !img.data("original-saved")) {
        img.data({
          "original-src": img.attr("src"),
          "original-srcset": img.attr("srcset") || "",
          "original-sizes": img.attr("sizes") || "",
          "original-saved": true,
        });
      }

      if (link && link.length && !link.data("original-href")) {
        link.data("original-href", link.attr("href"));
      }
    }

    /* Update image */
    function updateImage(img, data) {
      if (!img.length) return;
      img.attr({
        src: data.src || "",
        srcset: data.srcset || "",
        sizes: data.sizes || "",
      });
    }

    /* Restore */
    function restoreImage(img, fallback) {
      if (!img.length) return;

      var src = img.data("original-src") || fallback.src;
      var srcset = img.data("original-srcset") || fallback.srcset;
      var sizes = img.data("original-sizes") || fallback.sizes;

      img.attr("src", src || "");

      if (srcset) img.attr("srcset", srcset);
      else img.removeAttr("srcset");

      if (sizes) img.attr("sizes", sizes);
      else img.removeAttr("sizes");
    }

    /* Update Swiper (super smooth) */
    function updateSwiper() {
      if (!swiperProductGalleryDisplay) return;

      setTimeout(function () {
        swiperProductGalleryDisplay.update();
        swiperProductGalleryDisplay.slideTo(0, 300);
      }, 30);
    }

    /* Re-init lightbox */
    function reinitLightbox() {
      setTimeout(function() {
        ProductGalleryGLightboxInit();
      }, 150);
    }

    /* When variation found */
    function handleVariationFound(event, variation) {
      if (!variation || !variation.image) return;

      var urls = {
        full: variation.image.full_src || variation.image.src || "",
        thumb: variation.image.src || variation.image.thumbnail_src || variation.image.gallery_thumbnail_src || variation.image.full_src || "",
      };

      /* Featured */
      var featuredImg = $(selectors.featuredImage).first();
      var featuredLink = featuredImg.closest("a");

      if (featuredImg.length && urls.full) {
        saveOriginalToData(featuredImg, featuredLink);
        updateImage(featuredImg, { src: urls.full });
        
        // Update href for GLightbox
        featuredLink.attr("href", urls.full);
      }

      /* Thumbnail */
      var thumbImg = $(selectors.thumbnailImage).first();
      if (thumbImg.length && urls.thumb) {
        saveOriginalToData(thumbImg);
        updateImage(thumbImg, { src: urls.thumb });
      }

      updateSwiper();
      reinitLightbox(); // Re-init GLightbox with new href
    }

    /* Reset variation */
    function handleVariationReset() {
      var featuredImg = $(selectors.featuredImage).first();
      var featuredLink = featuredImg.closest("a");

      restoreImage(featuredImg, state.originalData.featured);

      var originalHref = featuredLink.data("original-href") || state.originalData.featured.href;

      if (originalHref) featuredLink.attr("href", originalHref);

      var thumbImg = $(selectors.thumbnailImage).first();
      restoreImage(thumbImg, state.originalData.thumbnail);

      updateSwiper();
      reinitLightbox(); // Re-init GLightbox with original href
    }

    /* Init */
    initOriginalData();

    $form.on("found_variation", handleVariationFound);
    $form.on("reset_data", handleVariationReset);
  });
})(jQuery);