(function () {
  'use strict';

  const highPerformance = {

    init() {
      this.searchToggle();
      this.textAnimation();
      this.headerMediaAnimation();
      this.productFilter();
      this.variation();
      this.textCarousel();
    },

    /* ---------------------------
     * HEADER SEARCH (ACCESSIBLE FIXED)
     * --------------------------- */
    searchToggle() {
      const searchContainer = document.querySelectorAll('.wp-primary-search');

      searchContainer.forEach((searchForm) => {
        if (!searchForm) return;

        const body = document.body;
        const toggleIcon = searchForm.querySelector('.wp-search-toggle-container');
        const searchInnerContainer = searchForm.querySelector('.wp-search-container');
        const searchInput = searchForm.querySelector('.wp-block-search__input');
        const fseSearch = document.querySelectorAll('.search-controller .svg, .social-controller .svg');

        /* ---------------------------
         * CLOSE OTHER SEARCH CONTROLLERS
         * --------------------------- */
        fseSearch.forEach((btn) => {
          btn.addEventListener('click', () => {
            body.classList.remove('show-search');
            searchForm.classList.remove('toggled-on');
            toggleIcon?.setAttribute('aria-expanded', 'false');
          });
        });

        /* ---------------------------
         * OPEN / CLOSE TOGGLE
         * --------------------------- */
        toggleIcon?.addEventListener('click', () => {
          const isOpen = searchForm.classList.toggle('toggled-on');
          body.classList.toggle('show-search');

          toggleIcon.setAttribute('aria-expanded', isOpen ? 'true' : 'false');

          if (isOpen) {
            setTimeout(() => searchInput?.focus(), 50);
          }
        });

        /* ---------------------------
         * ESC KEY SUPPORT (REQUIRED FOR REVIEW)
         * --------------------------- */
        document.addEventListener('keydown', (e) => {
          if (e.key === 'Escape' && searchForm.classList.contains('toggled-on')) {
            searchForm.classList.remove('toggled-on');
            body.classList.remove('show-search');

            toggleIcon?.setAttribute('aria-expanded', 'false');
            toggleIcon?.focus();
          }
        });

        /* ---------------------------
         * CLICK OUTSIDE TO CLOSE (FIXED)
         * --------------------------- */
        document.addEventListener('click', (e) => {
          const clickedInside =
            searchInnerContainer?.contains(e.target) ||
            toggleIcon?.contains(e.target);

          if (!clickedInside && searchForm.classList.contains('toggled-on')) {
            searchForm.classList.remove('toggled-on');
            body.classList.remove('show-search');

            toggleIcon?.setAttribute('aria-expanded', 'false');
          }
        });
      });
    },

    /* ---------------------------
     * TEXT ANIMATION
     * --------------------------- */
    textAnimation() {
      const textItems = document.querySelectorAll(".anim-text");

      textItems.forEach((item) => {
        const text = item.textContent;
        item.textContent = "";

        text.split("").forEach((char) => {
          item.innerHTML += `<span>${char}</span>`;
        });

        const startAnimation = () => {
          let char = 0;
          const spans = item.querySelectorAll("span");

          const timer = setInterval(() => {
            spans[char].classList.add("fade");
            char++;
            if (char === spans.length) clearInterval(timer);
          }, 50);
        };

        const observer = new MutationObserver(() => {
          if (item.classList.contains("show")) {
            startAnimation();
            observer.disconnect();
          }
        });

        observer.observe(item, { attributes: true });
      });
    },

    /* ---------------------------
     * HEADER MEDIA ANIMATION
     * --------------------------- */
    headerMediaAnimation() {
      const container = document.querySelector('.wp-block-custom-header-media');
      if (!container) return;

      const items = [
        { selector: '.wp-block-sub-heading', delay: 300 },
        { selector: '.anim-text', delay: 600 },
        { selector: '.wp-block-buttons', delay: 1400 }
      ];

      items.forEach(({ selector, delay }) => {
        const el = container.querySelector(selector);
        if (el) {
          setTimeout(() => {
            el.classList.add('show');
          }, delay);
        }
      });
    },

    /* ---------------------------
     * PRODUCT FILTER
     * --------------------------- */
    productFilter() {
      document.querySelectorAll('.wp-product-filter .wp-element-button').forEach(btn => {
        btn.addEventListener('click', (e) => {
          e.stopPropagation();
          document.body.classList.toggle('filter-on');
        });
      });

      document.addEventListener('click', (e) => {
        const f1 = document.querySelector('.wp-product-filter');
        const f2 = document.querySelector('.wp-block-woocommerce-product-filters');

        if ((!f1 || !f1.contains(e.target)) && (!f2 || !f2.contains(e.target))) {
          document.body.classList.remove('filter-on');
        }
      });
    },

    /* ---------------------------
     * PRODUCT VARIATIONS
     * --------------------------- */
    variation() {
      document.querySelectorAll('.variations select').forEach((select) => {
        const wrapper = document.createElement('div');
        wrapper.className = 'custom-variation';

        select.querySelectorAll('option').forEach((option) => {
          if (!option.value) return;

          const btn = document.createElement('div');
          btn.className = 'variation-option';
          btn.dataset.value = option.value;
          btn.textContent = option.textContent;

          btn.addEventListener('click', () => {
            wrapper.querySelectorAll('.variation-option')
              .forEach(el => el.classList.remove('active'));

            btn.classList.add('active');
            select.value = option.value;
            select.dispatchEvent(new Event('change', { bubbles: true }));
          });

          wrapper.appendChild(btn);
        });

        select.after(wrapper);
      });

      document.addEventListener('click', (e) => {
        if (e.target.closest('.reset_variations')) {
          document.querySelectorAll('.variation-option')
            .forEach(el => el.classList.remove('active'));
        }
      });
    },

    /* ---------------------------
     * TEXT CAROUSEL LOOP
     * --------------------------- */
    textCarousel() {
      const wrappers = document.querySelectorAll('.text-carousel-col');
      if (!wrappers.length) return;

      wrappers.forEach((loopWrapper) => {
        if (loopWrapper.dataset.carouselInit) return;
        loopWrapper.dataset.carouselInit = "true";

        const items = loopWrapper.querySelectorAll('.wp-block-column');
        if (!items.length) return;

        const track = document.createElement('div');
        track.classList.add('carousel-track');

        // Move original items into track
        items.forEach((item) => track.appendChild(item));
        loopWrapper.appendChild(track);

        // Wait for images to load before measuring
        const images = track.querySelectorAll('img');
        const imagePromises = Array.from(images).map(img => {
          if (img.complete) return Promise.resolve();
          return new Promise(resolve => {
            img.addEventListener('load', resolve);
            img.addEventListener('error', resolve);
          });
        });

        Promise.all(imagePromises).then(() => {
          const originalWidth = track.scrollWidth;
          const viewportWidth = window.innerWidth;

          // Clone enough times to fill at least 2x viewport
          const clonesNeeded = Math.ceil((viewportWidth * 2) / originalWidth) + 1;

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

          // Re-measure after cloning
          const totalWidth = originalWidth;
          const duration = totalWidth / 50; // adjust speed

          track.style.setProperty('--track-width', `-${originalWidth}px`);
          track.style.animationDuration = `${duration}s`;
        });

        loopWrapper.addEventListener('mouseenter', () => {
          track.style.animationPlayState = 'paused';
        });

        loopWrapper.addEventListener('mouseleave', () => {
          track.style.animationPlayState = 'running';
        });
      });
    }

  };

  document.addEventListener('DOMContentLoaded', () => {
    highPerformance.init();
  });

})();