/**
 * Custom JS for theme elements
 */

(function () {
  'use strict';

  const Drinkify = {
    init() {
      this.body = document.body;

      this.bindEvents();

      // CORE INIT
      this.navigationDelay();
      this.cartButtons();
      this.searchToggle();
      this.splitHeader();

      this.dragScroll();
      this.customScrollbar();
      this.newsletterWrap();

      this.viewportCheck();
      this.mobileMenu();
      this.mobileFilters();
      this.quantity();

      this.observeDOM();
    },

    /* ---------------------------
     * EVENTS
     * --------------------------- */
    bindEvents() {
      document.addEventListener('click', this.handleOutsideClick.bind(this), { passive: true });
      window.addEventListener('scroll', this.onScroll.bind(this), { passive: true });
      window.addEventListener('resize', this.onResize.bind(this));
      window.addEventListener('load', this.onLoad.bind(this));
    },

    /* ---------------------------
     * SAFE DOM HELPERS
     * --------------------------- */
    getSearchWrap() {
      return document.querySelector('.right-section .search-product');
    },

    getSearchButtons() {
      return document.querySelectorAll('.dummy-icon .wp-block-search__button');
    },

    /* ---------------------------
     * NAVIGATION ANIMATION
     * --------------------------- */
    navigationDelay() {
      document.querySelectorAll('.wp-block-navigation__container, .wp-block-page-list')
        .forEach(container => {
          Array.from(container.children).forEach(child => {
            const submenu = child.lastElementChild;

            if (submenu && submenu.classList?.contains('wp-block-navigation__submenu-container')) {
              submenu.classList.add('main-list');

              Array.from(submenu.children).forEach((item, i) => {
                item.style.transitionDelay = `${0.1 / (i + 1)}s`;
              });
            }
          });
        });
    },

    /* ---------------------------
     * CART BUTTONS
     * --------------------------- */
    cartButtons() {
      document.querySelectorAll('.add_to_cart_button').forEach(btn => {
        if (btn.dataset.bound) return;

        btn.dataset.bound = true;

        btn.addEventListener('click', () => {
          btn.textContent = 'Added to cart';
        });
      });
    },

    /* ---------------------------
     * SEARCH TOGGLE (SAFE)
     * --------------------------- */
    searchToggle() {
      const buttons = this.getSearchButtons();
      if (!buttons.length) return;

      buttons.forEach(btn => {
        if (btn.dataset.bound) return;

        btn.dataset.bound = true;

        btn.addEventListener('click', (e) => {
          e.preventDefault();
          e.stopPropagation();

          this.body.classList.toggle('search-toggle');

          // autofocus
          if (this.body.classList.contains('search-toggle')) {
            const input = this.getSearchWrap()?.querySelector('input[type="search"]');
            if (input) input.focus();
          }
        });
      });
    },

    /* ---------------------------
     * OUTSIDE CLICK (FIXED)
     * --------------------------- */
    handleOutsideClick(e) {
      const searchWrap = this.getSearchWrap();
      const mobileIcon = document.querySelector('.wp-mobile-icon-menu');

      if (!searchWrap) return;

      if (
        !searchWrap.contains(e.target) &&
        !e.target.closest('.dummy-icon') &&
        !e.target.closest('.wp-mobile-icon-menu')
      ) {
        this.body.classList.remove('search-toggle');
      }
    },

    /* ---------------------------
     * HEADER SPLIT
     * --------------------------- */
    splitHeader() {
      const lastItem = document.querySelector('.media-content .last-item');
      if (!lastItem || lastItem.dataset.split === '1') return;

      lastItem.dataset.split = '1';

      const chars = lastItem.textContent.split('');
      let result = '';

      chars.forEach(char => {
        result += char.trim() === '' ? '' : `<span>${char}</span>`;
      });

      lastItem.innerHTML = result;
    },

    /* ---------------------------
     * LOAD ANIMATION
     * --------------------------- */
    onLoad() {
      const spans = document.querySelectorAll('.last-item span');
      const img = document.querySelector('.header-image');
      const textWrap = document.querySelector('.last-item');

      if (img) {
        img.style.transform = 'translateX(0)';
        img.style.opacity = '1';
      }

      if (textWrap) {
        textWrap.style.opacity = '1';
      }

      spans.forEach((span, i) => {
        span.style.transitionDelay = `${i * 0.1}s`;
        span.style.transform = 'translateY(0)';
        span.style.opacity = '1';
      });
    },

    /* ---------------------------
     * DRAG SCROLL
     * --------------------------- */
    dragScroll() {
      document.querySelectorAll('.scroller-section .inner-wrap').forEach(container => {
        let down = false, startX = 0, scrollLeft = 0;

        container.addEventListener('pointerdown', e => {
          down = true;
          startX = e.clientX;
          scrollLeft = container.scrollLeft;
          container.classList.add('active');
        });

        document.addEventListener('pointermove', e => {
          if (!down) return;
          requestAnimationFrame(() => {
            container.scrollLeft = scrollLeft - (e.clientX - startX);
          });
        });

        document.addEventListener('pointerup', () => {
          down = false;
          container.classList.remove('active');
        });
      });
    },

    /* ---------------------------
     * CUSTOM SCROLLBAR
     * --------------------------- */
    customScrollbar() {
      document.querySelectorAll('.scroller-section .inner-wrap').forEach(container => {
        if (container.dataset.scrollbar) return;

        container.dataset.scrollbar = true;

        const track = document.createElement('div');
        const thumb = document.createElement('div');

        track.className = 'custom-scrollbar';
        thumb.className = 'custom-scrollbar-thumb';

        track.appendChild(thumb);
        container.parentElement.appendChild(track);

        container.addEventListener('scroll', () => {
          const ratio = container.scrollLeft / (container.scrollWidth - container.clientWidth);
          const max = track.offsetWidth - thumb.offsetWidth;
          thumb.style.transform = `translateX(${ratio * max}px)`;
        }, { passive: true });
      });
    },

    /* ---------------------------
     * NEWSLETTER WRAP
     * --------------------------- */
    newsletterWrap() {
      const form = document.querySelector('.tnp-subscription-minimal form');
      if (!form || form.dataset.wrapped) return;

      const btn = form.querySelector('.tnp-submit');
      if (!btn) return;

      form.dataset.wrapped = true;

      const wrap = document.createElement('div');
      wrap.className = 'input-wrap';

      btn.parentNode.insertBefore(wrap, btn);
      wrap.appendChild(btn);
    },

    /* ---------------------------
     * VIEWPORT CHECK
     * --------------------------- */
    viewportCheck() {
      this.sections = document.querySelectorAll('.wp-block-section');
      this.checkSections();
    },

    checkSections() {
      if (!this.sections) return;

      this.sections.forEach(el => {
        const rect = el.getBoundingClientRect();
        const mid = rect.top + rect.height / 2;

        if (mid >= 0 && mid <= window.innerHeight) {
          el.classList.add('transition-element');
        }
      });
    },

    onScroll() {
      this.checkSections();
      this.mobileMenuHandler();
    },

    onResize() {
      this.mobileMenuHandler();
    },

    /* ---------------------------
     * MOBILE MENU
     * --------------------------- */
    mobileMenu() {
      this.prevScroll = window.scrollY;
    },

    mobileMenuHandler() {
      const header = document.querySelector('.wp-mobile-icon-menu');
      if (!header) return;

      if (window.innerWidth >= 768) {
        header.style.transform = 'none';
        return;
      }

      const current = window.scrollY;

      header.style.transform =
        current <= this.prevScroll ? 'none' : 'translateY(100%)';

      this.prevScroll = current;
    },

    /* ---------------------------
     * MOBILE FILTER BUTTON
     * --------------------------- */

    mobileFilters() {

      document.querySelectorAll('.btn-mobile-filters')
        .forEach(btn => {

          if (btn.dataset.bound) return;

          btn.dataset.bound = true;

          btn.addEventListener('click', () => {
            btn.classList.toggle('toggled-on');
          });

        });

    },

    /* ---------------------------
     * QUANTITY
     * --------------------------- */
    quantity() {
      document.querySelectorAll('.quantity').forEach(wrap => {
        if (wrap.dataset.qty) return;

        wrap.dataset.qty = true;

        const input = wrap.querySelector('.qty');
        if (!input) return;

        const nav = document.createElement('div');
        const up = document.createElement('button');
        const down = document.createElement('button');

        nav.className = 'quantity-nav';
        up.className = 'quantity-button quantity-up';
        down.className = 'quantity-button quantity-down';

        up.type = down.type = 'button';
        up.textContent = '+';
        down.textContent = '-';

        nav.append(up, down);
        wrap.appendChild(nav);

        up.addEventListener('click', () => {
          input.stepUp();
          input.dispatchEvent(new Event('change', { bubbles: true }));
        });

        down.addEventListener('click', () => {
          input.stepDown();
          input.dispatchEvent(new Event('change', { bubbles: true }));
        });
      });
    },

    /* ---------------------------
     * OBSERVER
     * --------------------------- */
    observeDOM() {
      const observer = new MutationObserver(() => {
        this.cartButtons();
        this.quantity();
      });

      observer.observe(document.body, {
        childList: true,
        subtree: true
      });
    }
  };

  /* INIT SAFE */
  if (document.readyState !== 'loading') {
    Drinkify.init();
  } else {
    document.addEventListener('DOMContentLoaded', () => Drinkify.init());
  }

})();
