/**
 * Custom JS for theme elements
 */

// ADDED DELAY TO LIST ITEMS
const rockTuneDelayTime = () => {

  let time = 0.1;

  let content = document.querySelectorAll('.wp-block-navigation__container,.wp-block-page-list');
  if (content !== null) {
    content.forEach((item) => {
      let firstChild = item.childNodes /* Target every single child node of content element */
      firstChild.forEach(item => {
        let lastChild = item.lastChild;
        let ul = 'wp-block-navigation__submenu-container';
        if (lastChild.classList.contains(ul)) {   /* Check whether last child contains ul or not */
          let nestedChild = lastChild.children;
          Array.from(nestedChild).forEach((item, index) => {
            item.setAttribute("style", `transition-delay: ${time * index}s`);
          })
        }
      })
    })
  }
}

rockTuneDelayTime()

// SHOW SEARCH FOR WHILE CLICK SEARCH ICON

const rockTuneSearchModal = () => {

  const searchInput = document.querySelector('.right-section .search-product input[type="search"]');
  const mobileIcon = document.querySelector('.wp-mobile-icon-menu');
  const searchCont = document.querySelectorAll('.right-section');
  const searchDummy = document.querySelector('.dummy-icon .wp-block-search__button');
  const searchWrap = document.querySelector('.right-section .search-product');
  const rockTuneShowHandler = (e) => {
    e.preventDefault();
    let body = document.body;
    body.classList.toggle('search-toggle');
  }
  if (searchCont !== null) {
    searchCont.forEach((item) => {
      let searchBtn = document.querySelectorAll('.dummy-icon .wp-block-search__button')
      searchBtn.forEach((btn) => {
        btn.addEventListener('click', rockTuneShowHandler)
      })
    })
    if (mobileIcon !== null && searchDummy !== null && searchWrap !== null) {
      document.addEventListener('click', function (e) {
        if (!searchWrap.contains(e.target) && !searchDummy.contains(e.target) && !mobileIcon.contains(e.target)) {
          let body = document.body;
          body.classList.remove('search-toggle')
        }
      }
      )
    }
  }
}

// CREATE ELEMENT DIV TO WRAP EXISTING ELEM


window.addEventListener('DOMContentLoaded', function () {

  let divWrapper = document.querySelector('.tnp-subscription-minimal form');

  if (divWrapper !== null) {
    let appendIcon = document.querySelector('.tnp-subscription-minimal .tnp-submit');
    let newElem = document.createElement('div')
    newElem.classList.add('input-wrap');
    let innerAappend = newElem.appendChild(appendIcon)
    divWrapper.appendChild(newElem)
  }
})

// SHOW MOBILE MENU WHILE SCROLL UP

const rockTuneheader = document.querySelector('.wp-mobile-icon-menu');
if (rockTuneheader !== null) {
  // Variable to store the previous scroll position
  let previousScrollPos = window.pageYOffset || document.documentElement.scrollTop;

  // Function to check the scroll direction
  function rockTuneHandleScroll() {
    if (window.innerWidth < 768) {
      const currentScrollPos = window.pageYOffset || document.documentElement.scrollTop;

      if (currentScrollPos <= previousScrollPos) {
        // Scrolling up
        rockTuneheader.style.transform = 'none';
      } else {
        // Scrolling down or no movement
        rockTuneheader.style.transform = 'translateY(100%)';
      }

      // Update the previous scroll position
      previousScrollPos = currentScrollPos;
    } else {
      rockTuneheader.style.transform = 'none';
    }

    // Listen for the scroll event
  }
}

window.addEventListener('scroll', rockTuneHandleScroll);
window.addEventListener('load', rockTuneHandleScroll);
window.addEventListener('resize', rockTuneHandleScroll);


// DUPLICATE ITEMS ON TYPO SECTION

const rockTuneLoopScroll = () => {
  const loopWrapper = document.querySelector('.typo-cols');
  if (loopWrapper !== null) {
    const loopContent = document.querySelectorAll('.typo-cols .wp-block-column');
    const body = document.body;

    // Clone each image div and append with the "cloned" class
    loopContent.forEach((loopItem) => {
      const clone = loopItem.cloneNode(true);
      clone.classList.add('cloned');
      loopWrapper.appendChild(clone);
    });

    let isPaused = false;
    let firstCycleComplete = false;

    loopWrapper.addEventListener('mouseover', () => {
      isPaused = true;
    });

    loopWrapper.addEventListener('mouseout', () => {
      isPaused = false;
    });

    // Calculate the total width of all cloned items including flex gap
    const flexGap = getComputedStyle(loopWrapper).gap; // Get the flex gap
    const totalClonedWidth = Array.from(loopWrapper.querySelectorAll('.cloned')).reduce((acc, clonedItem, index) => {
      return acc + clonedItem.offsetWidth + parseFloat(flexGap);
    }, 0);

    function rockTuneScrollContent() {
      if (!isPaused) {
        const currentLeft = parseInt(loopWrapper.style.left) || 0;
        const totalWidth = totalClonedWidth + body.offsetWidth;

        loopWrapper.style.left = currentLeft - 1 + 'px';

        // Check if the first child of the cloned class div touches the starting position of the loopWrapper div
        if (currentLeft <= -totalClonedWidth && firstCycleComplete) {
          loopWrapper.style.left = '0';
        }

        // Mark the first cycle as complete after one complete cycle of scrolling
        if (currentLeft <= -totalWidth + body.offsetWidth) {
          firstCycleComplete = true;
        }
      }
    }

    setInterval(rockTuneScrollContent, 20);
  }
};


window.addEventListener('load', rockTuneLoopScroll())
window.addEventListener('resize', rockTuneLoopScroll())

// WRAP product title and price in new div for latest product section
const rockTuneCloneProductElem = (cloneElements) => {
  let productDivs = document.querySelectorAll(`.${cloneElements} .wp-block-column`)
  if (productDivs !== null) {
    productDivs.forEach((productDiv) => {

      let productInfoWrap = document.createElement('div')
      productInfoWrap.classList.add('wp-product-info-wrap')
      const featuredProductWrap = productDiv.querySelector('.wc-block-featured-product__wrapper');
      const featuredCategoryWrap = productDiv.querySelector('.wc-block-featured-category__wrapper');
      if (featuredProductWrap) {
        featuredProductWrap.appendChild(productInfoWrap)
      }
      if (featuredCategoryWrap) {
        featuredCategoryWrap.appendChild(productInfoWrap)
      }
      if (cloneElements === 'featured-product-section') {
        let productDesc = productDiv.querySelector(`.wc-block-featured-product__description`)
        let productImage = productDiv.querySelector('.wc-block-featured-product__background-image')
        let productPrice = productDiv.querySelector('.wc-block-featured-product__price')
        let productTitle = productDiv.querySelector('.wc-block-featured-product__title')
        let productReview = productDiv.querySelector('.wc-block-featured-product__rating')
        if (productTitle !== null) {
          productInfoWrap.appendChild(productTitle)
        }

        if (productDesc !== null) {
          productInfoWrap.appendChild(productDesc)
        }

        if (productPrice !== null) {
          productInfoWrap.appendChild(productPrice)
        }

        if (productReview !== null) {
          productInfoWrap.appendChild(productReview)
        }

        if (productInfoWrap !== null) {
          if (productImage !== null) {
            productImage.after(productInfoWrap)
          }
        }
      }

      if (cloneElements === 'featured-cat-section') {
        let productDesc = productDiv.querySelector(`.wc-block-featured-category__description`)
        let productImage = productDiv.querySelector('.wc-block-featured-category__background-image')
        let productPrice = productDiv.querySelector('.wc-block-featured-category__price')
        let productTitle = productDiv.querySelector('.wc-block-featured-category__title')
        let productReview = productDiv.querySelector('.wc-block-featured-category__rating')

        if (productTitle !== null) {
          productInfoWrap.appendChild(productTitle)
        }

        if (productDesc !== null) {
          productInfoWrap.appendChild(productDesc)
        }

        if (productPrice !== null) {
          productInfoWrap.appendChild(productPrice)
        }

        if (productReview !== null) {
          productInfoWrap.appendChild(productReview)
        }

        if (productInfoWrap !== null) {
          if (productImage !== null) {
            productImage.after(productInfoWrap)
          }
        }
      }


    })
  }
}

rockTuneCloneProductElem('featured-product-section')
rockTuneCloneProductElem('featured-cat-section')


// Assign padding top to banner equal to header
const rockTuneCalculateHeight = () => {
  let transparentHeader = document.querySelectorAll('.transparent-header');
  let bannerOffset = document.querySelector('.banner .wp-block-cover');
  if (bannerOffset !== null) {
    transparentHeader.forEach((absHeader) => {
      let transparentHeaderHeight = absHeader.clientHeight;
      bannerOffset.setAttribute('style', `padding-top: ${transparentHeaderHeight}px`);
    })
  }
};


window.addEventListener('resize', rockTuneCalculateHeight)
window.addEventListener('load', rockTuneCalculateHeight())


/**
 * Header Search Show/Hide js
 */

const rockTunePrimarySearchModal = () => {

  let searchContainer = document.querySelectorAll('.wp-primary-search');
  const mobileIcon = document.querySelector('.wp-mobile-icon-menu');

  searchContainer.forEach((searchForm) => {
    let body = document.body;
    if (searchForm !== null) {
      let toggleIcon = searchForm.querySelector('.wp-search-toggle-container')
      let searchInnerContainer = searchForm.querySelector('.wp-search-container')
      let searchInput = searchForm.querySelector('.wp-block-search__input')
      let fseSearch = document.querySelectorAll('.search-controller .svg, .social-controller .svg')
      let body = document.body;

      fseSearch.forEach((searchButton) => {
        searchButton.addEventListener('click', function () {
          console.log('clicked')
          body.classList.remove('show-search')
          searchForm.classList.remove('toggled-on')
        })
      })

      toggleIcon.addEventListener('click', function () {
        searchForm.classList.toggle('toggled-on')
        body.classList.toggle('show-search')
        searchInput.focus()
      })

      document.addEventListener('click', function (e) {
        if (!searchInput.contains(e.target) && !mobileIcon.contains(e.target) && !searchInnerContainer.contains(e.target) && !toggleIcon.contains(e.target) && searchForm.classList.contains('toggled-on')) {
          searchForm.classList.remove('toggled-on')
          body.classList.remove('show-search')
        }
      })
    }
  })
}


rockTunePrimarySearchModal()