(function () {
  'use strict';

  // Single state object
  const WillroReviews = {
    currentSlideIndex: 0,
    currentlyPlayingVideo: null,
    dropdownsBound: false,
    readMoreBound: false,
    videoPlayersBound: false,

    init() {
      this.initSkeletonRemoval();
      this.initDropdowns();
      this.initReadMore();
      this.initVideoPlayers();
      this.initSlider();
      this.initHoverRating();
      this.initAutoload();
    },

    initHoverRating() {
      const containers = document.querySelectorAll('.review-input-stars');
      if (!containers || containers.length === 0) return;

      // Helper to get color based on rating (Red -> Blue)
      function getColor(rating) {
        if (rating <= 1) return '#FF3722';
        if (rating <= 2) return '#FF8622';
        if (rating <= 3) return '#FFCE00';
        if (rating <= 4) return '#73CF11';
        return '#27AAE1';
      }
      function getBgEl(starEl) {
        return starEl.querySelector('.star-bg') || starEl.querySelector('rect') || starEl.querySelector('path');
      }
      containers.forEach(starsContainer => {
        if (starsContainer.dataset.hoverInit === '1') return;
        starsContainer.dataset.hoverInit = '1';

        const stars = starsContainer.querySelectorAll('.rating-star-link');

        stars.forEach(star => {
          star.addEventListener('mouseenter', function () {
            const hoverRating = parseInt(this.getAttribute('data-rating'));
            const activeColor = getColor(hoverRating);

            stars.forEach(s => {
              const starRating = parseInt(s.getAttribute('data-rating'));
              const bg = getBgEl(s);
              if (!bg) return;
              if (starRating <= hoverRating) {
                bg.setAttribute('fill', activeColor);
              } else {
                bg.setAttribute('fill', '#E4E7EC');
              }
            });
          });

          star.addEventListener('mouseleave', function () {
            stars.forEach(s => {
              const bg = getBgEl(s);
              if (!bg) return;
              bg.setAttribute('fill', '#E4E7EC');
            });
          });
        });

        starsContainer.addEventListener('mouseleave', function () {
          stars.forEach(s => {
            const bg = getBgEl(s);
            if (!bg) return;
            bg.setAttribute('fill', '#E4E7EC');
          });
        });
      });
    },

    initSkeletonRemoval() {
      const hasContent = document.querySelector('.willro-reviews-content');
      if (hasContent) {
        document.querySelectorAll('.willro-skeleton').forEach(el => el.remove());
        document.querySelectorAll('.willro-reviews-content').forEach(el => {
          el.style.display = 'block';
        });
      }
    },

    initAutoload() {
      let attempts = 0;
      const maxAttempts = 60; // ~6s
      const timer = setInterval(() => {
        attempts++;
        const wrappers = document.querySelectorAll('.willro-reviews-wrapper[data-autoload="1"]');
        const canReload = typeof window.reloadWillroReviews === 'function' && typeof WillroReviewsData !== 'undefined' && typeof window.jQuery !== 'undefined';
        if (wrappers.length && canReload) {
          wrappers.forEach((w) => window.reloadWillroReviews(jQuery(w)));
          clearInterval(timer);
        }
        if (attempts >= maxAttempts) {
          clearInterval(timer);
        }
      }, 100);
    },

    initDropdowns() {
      if (this.dropdownsBound) return;
      this.dropdownsBound = true;

      // Use event delegation instead of multiple listeners
      document.addEventListener('click', (e) => {
        const dropdownBtn = e.target.closest('.dropdown-btn');

        if (dropdownBtn) {
          e.stopPropagation();
          const parent = dropdownBtn.closest('.dropdown');
          const isOpen = parent?.classList.contains('open');

          // Close all dropdowns
          document.querySelectorAll('.dropdown.open').forEach(dropdown => {
            dropdown.classList.remove('open');
          });

          // Open clicked dropdown if it was closed
          if (parent && !isOpen) {
            parent.classList.add('open');
          }
        } else if (!e.target.closest('.dropdown')) {
          // Close all when clicking outside
          document.querySelectorAll('.dropdown.open').forEach(dropdown => {
            dropdown.classList.remove('open');
          });
        }
      }, { passive: true });
    },

    initReadMore() {
      if (this.readMoreBound) return;
      this.readMoreBound = true;

      // Use event delegation
      document.addEventListener('click', (e) => {
        const btn = e.target.closest('.read-more-btn');
        if (!btn) return;

        e.preventDefault();
        e.stopPropagation();

        const contentEl = btn.closest('.review-content');
        if (!contentEl) return;

        const full = contentEl.getAttribute('data-full') || '';
        const short = contentEl.getAttribute('data-short') || '';
        const textEl = contentEl.querySelector('.review-text') || contentEl;

        if (!full) return;

        if (contentEl.classList.contains('expanded')) {
          textEl.textContent = short || full;
          btn.textContent = (typeof WillroReviewsData !== 'undefined' && WillroReviewsData?.i18n?.seeMore) ? WillroReviewsData.i18n.seeMore : 'See More';
          contentEl.classList.remove('expanded');
        } else {
          textEl.textContent = full;
          btn.textContent = (typeof WillroReviewsData !== 'undefined' && WillroReviewsData?.i18n?.seeLess) ? WillroReviewsData.i18n.seeLess : 'See Less';
          contentEl.classList.add('expanded');
        }
      });
    },

    initVideoPlayers() {
      if (this.videoPlayersBound) return;
      this.videoPlayersBound = true;

      // Use event delegation for video controls
      document.addEventListener('click', (e) => {
        const playBtn = e.target.closest('[data-play-btn]');
        const videoWrapper = e.target.closest('[willro-data-video-wrapper]');

        if (playBtn && videoWrapper) {
          e.stopPropagation();
          const video = videoWrapper.querySelector('[data-review-video]');
          const overlay = videoWrapper.querySelector('[data-video-overlay]');
          this.playVideo(video, overlay);
        } else if (videoWrapper) {
          const video = videoWrapper.querySelector('[data-review-video]');
          const overlay = videoWrapper.querySelector('[data-video-overlay]');

          if (video.paused) {
            this.playVideo(video, overlay);
          } else {
            this.pauseVideo(video, overlay);
          }
        }
      });

      // Video ended event
      document.addEventListener('ended', (e) => {
        if (e.target.matches('[data-review-video]')) {
          const wrapper = e.target.closest('[willro-data-video-wrapper]');
          const overlay = wrapper?.querySelector('[data-video-overlay]');
          if (overlay) this.pauseVideo(e.target, overlay);
        }
      }, true);
    },

    playVideo(video, overlay) {
      if (!video || !overlay) return;

      // Pause currently playing video
      if (this.currentlyPlayingVideo && this.currentlyPlayingVideo !== video) {
        const prevWrapper = this.currentlyPlayingVideo.closest('[willro-data-video-wrapper]');
        const prevOverlay = prevWrapper?.querySelector('[data-video-overlay]');
        if (prevOverlay) this.pauseVideo(this.currentlyPlayingVideo, prevOverlay);
      }

      video.play();
      video.classList.add('playing');
      video.setAttribute('controls', 'controls');
      overlay.classList.add('hidden');
      this.currentlyPlayingVideo = video;
    },

    pauseVideo(video, overlay) {
      if (!video || !overlay) return;

      video.pause();
      video.classList.remove('playing');
      video.removeAttribute('controls');
      overlay.classList.remove('hidden');

      if (this.currentlyPlayingVideo === video) {
        this.currentlyPlayingVideo = null;
      }
    },

    initSlider() {
      const wrappers = document.querySelectorAll('.willro-reviews-wrapper');
      if (!wrappers || wrappers.length === 0) return;

      wrappers.forEach((wrapper) => {
        const track = wrapper.querySelector('#track');
        if (!track) return;

        if (track.dataset.willroSliderInit === '1') return;
        track.dataset.willroSliderInit = '1';

        const getOriginalItems = () => track.querySelectorAll('.review-card-link:not(.clone)');
        let originalItems = Array.from(getOriginalItems());

        if (originalItems.length === 0) return;

        track.querySelectorAll('.clone').forEach(el => el.remove());

        const needsSlider = originalItems.length >= 3;

        const prevBtn = wrapper.querySelector('.slider-btn.prev');
        const nextBtn = wrapper.querySelector('.slider-btn.next');
        const leftArrow = wrapper.querySelector('.left-arrow');
        const rightArrow = wrapper.querySelector('.right-arrow');

        if (!needsSlider) {
          if (prevBtn) prevBtn.style.display = 'none';
          if (nextBtn) nextBtn.style.display = 'none';
          if (leftArrow) leftArrow.style.display = 'none';
          if (rightArrow) rightArrow.style.display = 'none';
          track.style.transform = 'translateX(0px)';
          return;
        }

        if (prevBtn) prevBtn.style.display = 'flex';
        if (nextBtn) nextBtn.style.display = 'flex';
        if (leftArrow) leftArrow.style.display = 'flex';
        if (rightArrow) rightArrow.style.display = 'flex';

        for (let i = 0; i < 2; i++) {
          originalItems.forEach(item => {
            const clone = item.cloneNode(true);
            clone.classList.add('clone');
            track.appendChild(clone);
          });
        }

        let currentPosition = 0;
        let isTransitioning = false;

        const moveSlide = (direction) => {
          if (isTransitioning) return;

          const allItems = track.querySelectorAll('.review-card-link');
          const originalCount = originalItems.length;
          const cardWidth = allItems[0]?.offsetWidth ? (allItems[0].offsetWidth + 16) : 0;
          if (!cardWidth) return;

          isTransitioning = true;
          currentPosition += direction;

          track.style.transition = 'transform 0.5s ease-in-out';
          track.style.transform = `translateX(-${currentPosition * cardWidth}px)`;

          setTimeout(() => {
            if (currentPosition >= originalCount) {
              track.style.transition = 'none';
              currentPosition = currentPosition % originalCount;
              track.style.transform = `translateX(-${currentPosition * cardWidth}px)`;
            }

            if (currentPosition < 0) {
              track.style.transition = 'none';
              currentPosition = originalCount + currentPosition;
              track.style.transform = `translateX(-${currentPosition * cardWidth}px)`;
            }

            isTransitioning = false;
          }, 500);
        };

        wrapper.willroMoveSlide = moveSlide;

        track.style.transform = 'translateX(0px)';

        if (prevBtn && prevBtn.dataset.willroSliderBound !== '1') {
          prevBtn.dataset.willroSliderBound = '1';
          prevBtn.addEventListener('click', () => moveSlide(-1));
        }
        if (nextBtn && nextBtn.dataset.willroSliderBound !== '1') {
          nextBtn.dataset.willroSliderBound = '1';
          nextBtn.addEventListener('click', () => moveSlide(1));
        }
        if (leftArrow && leftArrow.dataset.willroSliderBound !== '1') {
          leftArrow.dataset.willroSliderBound = '1';
          leftArrow.addEventListener('click', (e) => {
            e.preventDefault();
            moveSlide(-1);
          });
        }
        if (rightArrow && rightArrow.dataset.willroSliderBound !== '1') {
          rightArrow.dataset.willroSliderBound = '1';
          rightArrow.addEventListener('click', (e) => {
            e.preventDefault();
            moveSlide(1);
          });
        }

        if (wrapper.dataset.willroSliderResizeBound !== '1') {
          wrapper.dataset.willroSliderResizeBound = '1';
          let resizeTimeout;
          window.addEventListener('resize', () => {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(() => {
              const allItems = track.querySelectorAll('.review-card-link');
              if (allItems.length > 0) {
                const cardWidth = allItems[0]?.offsetWidth ? (allItems[0].offsetWidth + 16) : 0;
                if (!cardWidth) return;
                track.style.transition = 'none';
                track.style.transform = `translateX(-${currentPosition * cardWidth}px)`;
              }
            }, 150);
          });
        }
      });

      window.moveSlide = (direction) => {
        const firstWrapper = document.querySelector('.willro-reviews-wrapper');
        if (firstWrapper && typeof firstWrapper.willroMoveSlide === 'function') {
          firstWrapper.willroMoveSlide(direction);
        }
      };
},

    reinit() {
      this.initSkeletonRemoval();
      this.initDropdowns();
      this.initReadMore();
      this.initVideoPlayers();
      this.initSlider();
      this.initHoverRating();
    }
  };

  // Initialize on page load
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => WillroReviews.init());
  } else {
    WillroReviews.init();
  }

  // Expose reinit for AJAX/PJAX
  window.initWillroReviews = () => WillroReviews.reinit();

  // AJAX/PJAX support
  document.addEventListener('ajaxComplete', () => WillroReviews.reinit());
  document.addEventListener('turbo:load', () => WillroReviews.reinit());

})();

// jQuery AJAX filtering (kept separate as it's using jQuery)
(function ($) {
  'use strict';

  function getFilters(wrapper) {
    const data = {
      action: 'willro_filter_reviews',
      template: wrapper.data('template'),
      limit: wrapper.data('limit'),
      page: parseInt(wrapper.attr('data-page')) || 1,
    };

    const nonce = (typeof WillroReviewsData !== 'undefined' && WillroReviewsData && WillroReviewsData.nonce) ? WillroReviewsData.nonce : '';
    if (nonce) data.nonce = nonce;

    const ratingText = wrapper.find('input[name="rating"]:checked').parent().text().trim();
    if (ratingText && ratingText.toLowerCase() !== 'all') {
      const m = ratingText.match(/\d+/);
      if (m) data.rating = parseInt(m[0], 10);
    } else {
      const dr = wrapper.attr('data-rating');
      if (dr && dr !== 'ALL') {
        const dm = String(dr).match(/\d+/);
        if (dm) data.rating = parseInt(dm[0], 10); else data.rating = dr;
      }
    }

    // Sort
    const sort = wrapper.find('input[name="sort"]:checked').val();
    if (sort) {
      const sortMap = {
        MOST_RELEVANT: 'MOST_RELEVANT',
        HIGHEST_REVIEWS: 'HIGHEST_REVIEWS',
        LOWEST_REVIEWS: 'LOWEST_REVIEWS',
        RECENT_REVIEWS: 'RECENT_REVIEWS',
        RECENT_WITH_MIN_ONE_REVIEW: 'RECENT_WITH_MIN_ONE_REVIEW',
      };
      data.sortType = sortMap[sort];
    } else {
      const ds = wrapper.attr('data-sortType') || wrapper.attr('data-sorttype');
      if (ds) data.sortType = ds;
    }

    // Media
    const media = wrapper.find('input[name="mediaType"]:checked').val();
    if (media) {
      data.mediaType = media;
    } else {
      const dm = wrapper.attr('data-mediaType') || wrapper.attr('data-mediatype');
      if (dm && dm !== 'ALL') data.mediaType = dm;
    }

    return data;
  }

  function reloadTemplate(wrapper) {
    const data = getFilters(wrapper);
    const wrapperHeight = wrapper.height();

    // Set loading state
    wrapper.css({
      'position': 'relative',
      'min-height': wrapperHeight
    });

    // Remove old skeleton
    wrapper.find('.willro-skeleton').remove();

    // Load and show skeleton
    const localizedSkeletonHtml = (typeof WillroReviewsData !== 'undefined' && WillroReviewsData && WillroReviewsData.skeletonHtml) ? WillroReviewsData.skeletonHtml : '';
    if (localizedSkeletonHtml) {
      const $skeleton = $('<div class="willro-skeleton"></div>')
        .html(localizedSkeletonHtml)
        .css({
          position: 'absolute',
          top: 0,
          left: 0,
          width: '100%',
          height: '100%',
          background: '#fff',
          'z-index': 999
        });
      wrapper.append($skeleton);
    } else if (typeof WillroReviewsData !== 'undefined' && WillroReviewsData?.skeletonUrl) {
      $.get(WillroReviewsData.skeletonUrl, function (skeletonHtml) {
        const $skeleton = $('<div class="willro-skeleton"></div>')
          .html(skeletonHtml)
          .css({
            position: 'absolute',
            top: 0,
            left: 0,
            width: '100%',
            height: '100%',
            background: '#fff',
            'z-index': 999
          });
        wrapper.append($skeleton);
      });
    }

    // Fetch filtered reviews
    $.post(WillroReviewsData.ajaxUrl, data, function (html) {
      const $newWrapper = $(html);

      // Preserve wrapper attributes
      const oldAttrs = {};
      $.each(wrapper[0].attributes, function (i, attr) {
        oldAttrs[attr.name] = attr.value;
      });

      wrapper.replaceWith($newWrapper);

      // Re-apply attributes
      const newWrapper = $('.willro-reviews-wrapper[data-template="' + data.template + '"]');
      $.each(oldAttrs, function (name, value) {
        newWrapper.attr(name, value);
      });

      // Re-initialize
      if (window.initWillroReviews) {
        window.initWillroReviews();
      }
    });
  }

  window.reloadWillroReviews = reloadTemplate;

  // Filter change event (event delegation)
  $(document).on('change', '.willro-reviews-wrapper input[type="radio"]', function () {
    reloadTemplate($(this).closest('.willro-reviews-wrapper'));
  });

})(jQuery);
