/**
 * Custom JS for theme elements
 */

/**
 *
 *  ADDED DELAY TO LIST ITEMS
 *
 */


let pawsCentralTime = 0.1;

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

function pawsCentralTimer(targetClass) {
  let pawsCentralOfferContent = document.querySelectorAll(`.${targetClass}`);
  if (pawsCentralOfferContent !== null) {
    pawsCentralOfferContent.forEach((item, index) => {
      let offerTime = 0.3;
      item.setAttribute("style", `transition-delay: ${offerTime * index}s`);
    })
  }
}

pawsCentralTimer('content')
pawsCentralTimer('recent-product-section .wc-block-grid__product')
pawsCentralTimer('recent-product-section .wc-block-product')
pawsCentralTimer('services-section .wp-block-column')

// SHOW SEARCH FOR WHILE CLICK SEARCH ICON

const pawsCentralSearchInput = document.querySelector('.right-section .search-product input[type="search"]');
const pawsCentralMobileIcon = document.querySelector('.wp-mobile-icon-menu');
const pawsCentralSearchCont = document.querySelectorAll('.right-section');
const pawsCentralSearchDummy = document.querySelector('.dummy-icon .wp-block-search__button');
const pawsCentralSearchWrap = document.querySelector('.right-section .search-product');
const pawsCentralShowHandler = (e) => {
  e.preventDefault();
  let pawsCentralBody = document.body;
  pawsCentralBody.classList.toggle('search-toggle');
}
if (pawsCentralSearchCont !== null) {
  pawsCentralSearchCont.forEach((item) => {
    let pawsCentralSearchBtn = document.querySelectorAll('.dummy-icon .wp-block-search__button')
    pawsCentralSearchBtn.forEach((btn) => {
      btn.addEventListener('click', pawsCentralShowHandler)
    })
  })
  if (pawsCentralMobileIcon !== null && pawsCentralSearchDummy !== null && pawsCentralSearchWrap !== null) {
    document.addEventListener('click', function (e) {
      if (!pawsCentralSearchWrap.contains(e.target) && !pawsCentralSearchDummy.contains(e.target) && !pawsCentralMobileIcon.contains(e.target)) {
        let pawsCentralBody = document.body;
        pawsCentralBody.classList.remove('search-toggle')

      }
    }
    )
  }
}

window.addEventListener('load', function () {
  let pawsCentralMediaTitles = document.querySelectorAll('.media-content h2')
  let pawsCentralMediaContent = document.querySelector('.media-content p')
  let pawsCentralMediaButtons = document.querySelectorAll('.media-content .wp-block-button')
  if (pawsCentralMediaTitles && pawsCentralMediaContent && pawsCentralMediaButtons !== null) {
    pawsCentralMediaButtons.forEach((button) => {
      button.setAttribute('style', `transform: translateY(0)`)
      button.style.opacity = 1;
      button.style.clipPath = 'polygon(0 0, 100% 0, 100% 100%, 0 100%)'

    })
    pawsCentralMediaContent.setAttribute('style', `transform: translateY(0)`)
    pawsCentralMediaContent.style.opacity = 1;
    pawsCentralMediaContent.style.clipPath = 'polygon(0 0, 100% 0, 99% 100%, 0 100%)'
    pawsCentralMediaTitles.forEach((title) => {
      title.setAttribute('style', `transform: translateY(0)`)
      title.style.opacity = 1;
      title.style.clipPath = 'polygon(0 0, 100% 0, 100% 100%, 0 100%)'

    })
  }
})

/**
 * Scroll to JS for scroll and drag  horizontal on scroller sections
 *
 *
 */

const drinkifySellerSection = document.querySelectorAll(".scroller-section .inner-wrap");

if (drinkifySellerSection.length > 0) {
  drinkifySellerSection.forEach((container) => {
    let isDragging = false;
    let startX = 0;
    let scrollStart = 0;
    let animationFrameId = null;

    const onPointerDown = (e) => {
      isDragging = true;
      startX = e.clientX;
      scrollStart = container.scrollLeft;
      container.classList.add("active");

      // Prevent default to stop text selection
      e.preventDefault();

      document.addEventListener("pointermove", onPointerMove);
      document.addEventListener("pointerup", onPointerUp);
    };

    const onPointerMove = (e) => {
      if (!isDragging) return;

      const deltaX = e.clientX - startX;

      cancelAnimationFrame(animationFrameId);
      animationFrameId = requestAnimationFrame(() => {
        container.scrollLeft = scrollStart - deltaX;
      });
    };

    const onPointerUp = () => {
      isDragging = false;
      container.classList.remove("active");

      document.removeEventListener("pointermove", onPointerMove);
      document.removeEventListener("pointerup", onPointerUp);
    };

    container.addEventListener("pointerdown", onPointerDown);
  });
}

//for scroll progress bar
const containers = document.querySelectorAll('.scroller-section .inner-wrap');

containers.forEach((container) => {
  if (container) {
    // Create scrollbar elements
    const track = document.createElement('div');
    track.className = 'custom-scrollbar';

    const thumb = document.createElement('div');
    thumb.className = 'custom-scrollbar-thumb';
    track.appendChild(thumb);

    // Append to container's parent
    container.parentElement.style.position = 'relative'; // ensure it's positioned
    container.parentElement.appendChild(track);

    // Update thumb position on scroll
    container.addEventListener('scroll', () => {
      const scrollRatio = container.scrollLeft / (container.scrollWidth - container.clientWidth);
      const maxOffset = 280 - (280 * 0.3); // adjust this as per your thumb width ratio
      thumb.style.transform = `translateX(${scrollRatio * maxOffset}px)`;
    });
  }
});



/**
 *
 *  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)
  }
})


/**
 *
 *  ADD CLASS WHILE SECTION IS IN VIEWPORT
 *
 */

function isInViewport(elem) {
  const distance = elem.getBoundingClientRect();
  const windowHeight = window.innerHeight || document.documentElement.clientHeight;

  // middle (adjust divisor if needed)
  const elementMiddle = distance.top + distance.height / 2;

  return elementMiddle >= 0 && elementMiddle <= windowHeight;
}

const sections = document.querySelectorAll('.wp-block-section');

function checkSections() {
  sections.forEach(section => {
    if (isInViewport(section)) {
      section.classList.add('transition-element');
    }
  });
}

if (sections.length) {
  // run immediately
  checkSections();

  // run on scroll
  window.addEventListener('scroll', checkSections, { passive: true });

  // run on resize
  window.addEventListener('resize', checkSections);
}


/*
*
*
// SHOW TRANSPARENT HEADER WHILE SCROLL UP
*
*/

const pawsCentralHeader = document.querySelectorAll('.wp-mobile-icon-menu');
let pawsCentralPreviousScrollPos = window.pageYOffset || document.documentElement.scrollTop;

function pawsCentralHandleScroll() {
  pawsCentralHeader.forEach((headerScroll) => {
    const pawsCentralCurrentScrollPos = window.pageYOffset || document.documentElement.scrollTop;

    if (window.innerWidth < 1200) {
      if (pawsCentralCurrentScrollPos <= pawsCentralPreviousScrollPos) {
        // Scrolling up
        headerScroll.style.transform = 'none';
      } else {
        // Scrolling down or no movement
        headerScroll.style.transform = 'translateY(100%)';
      }

      pawsCentralPreviousScrollPos = pawsCentralCurrentScrollPos;
    } else {
      headerScroll.style.transform = 'none';
    }
  });
}

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


// RATING

const pawsCentralRatingAppend = (ratingDiv) => {
  const pawsCentralRatingWrap = document.querySelectorAll(`.${ratingDiv}`)
  if (pawsCentralRatingWrap !== null) {
    pawsCentralRatingWrap.forEach((wrap) => {
      const pawsCentralRatingNumbers = wrap.querySelector('strong.rating')
      wrap.appendChild(pawsCentralRatingNumbers)
    })
  }
}

pawsCentralRatingAppend('star-rating')

// SHOW LOADER TILL ALL DOCUMENT LOAD AND HIDE

window.onload = function () {
  const pawsCentralLoaders = document.querySelectorAll(".loader");
  if (pawsCentralLoaders !== null) {
    // Hide the loader (if not already hidden)
    pawsCentralLoaders.forEach((loader) => {
      loader.style.opacity = 0;
      loader.style.visibility = 'hidden';
    })
  }
};

// ADD CUSTOM CSS FOR SHOWING CURRENT_MENU_ITEM CLASS

document.body.querySelectorAll('.wp-block-navigation').forEach(function (navBlock) {
  if (navBlock !== null) {
    navBlock.querySelectorAll('[href="' + window.location.href + '"]').forEach(function (navActiveLink) {
      navActiveLink.parentNode.classList.add('current-nav-item');
    });
  }
});

// Function to Add/remove class for mobile Woocommerce sidebar Widgets/filters
const toggleFunc = (targetElem) => {
  let filterButtons = document.querySelectorAll(targetElem);

  filterButtons.forEach((filterButton) => {
    if (filterButton !== null) {
      filterButton.addEventListener("click", () => {
        if (filterButton.classList.contains("toggled-on")) {
          // if has 'toggled-on' class remove class
          filterButton.classList.remove("toggled-on");
        } else {
          // otherwise add 'toggled-on' class
          filterButton.classList.add("toggled-on");
        }
      });
    }
  });
};

toggleFunc(".btn-mobile-filters");

// Plus minus function added on product input counter
function wooQtyChange() {
  let qtyWrap = document.querySelectorAll('.quantity');
  qtyWrap.forEach((wrap) => {
    let qNav = document.createElement('div');
    let qUp = document.createElement('div');
    let qDown = document.createElement('div');
    let input = wrap.querySelectorAll('.qty');
    qUp.innerHTML = '+';
    qDown.innerHTML = '-';
    qNav.appendChild(qUp);
    qNav.appendChild(qDown);
    wrap.appendChild(qNav)
    qUp.setAttribute('class', 'quantity-button quantity-up');
    qDown.setAttribute('class', 'quantity-button quantity-down');
    max = 99999;
    let min = '';
    input.forEach((inputItem) => {
      min = inputItem.getAttribute('min');
      if (qtyWrap.length > 1) {
        // Set default value to 0
        inputItem.value = 0;
      }
      qNav.setAttribute('class', 'quantity-nav');
      let btnUp = wrap.querySelectorAll('.quantity-up');
      btnUp.forEach((btnItem) => {
        btnItem.addEventListener('click', function () {
          let oldValue = parseFloat(inputItem.value);
          if (oldValue >= max) {
            var newVal = oldValue;
          } else {
            var newVal = oldValue + 1;
          }
          inputItem.value = newVal
          var element = document.createEvent('HTMLEvents');
          var event = new Event('change', {
            bubbles: true
          });
          inputItem.dispatchEvent(event);
          return event;
        })
      })
      let btnDown = wrap.querySelectorAll('.quantity-down');
      btnDown.forEach((btnItem) => {
        btnItem.addEventListener('click', function () {
          let oldValue = parseFloat(inputItem.value);
          if (oldValue >= max) {
            var newVal = oldValue;
          } else if (oldValue <= 0) {
            var newVal = 0;
          } else {
            var newVal = oldValue - 1;
          }
          inputItem.value = newVal
          var element = document.createEvent('HTMLEvents');
          var event = new Event('change', {
            bubbles: true
          });
          inputItem.dispatchEvent(event);
          return event;
        })
      })
    })
  })
}
wooQtyChange();

function wooCartUpdate() {
  let btnTrigger = document.querySelector('button[name="update_cart"]');
  if (btnTrigger !== null) {
    btnTrigger.addEventListener('click', function () {
      setTimeout(function () {
        wooQtyChange();
      }, 5000);
      setTimeout(function () {
        wooCartUpdate();
      }, 5000);
    });
  }
}
wooCartUpdate();
