(function () {

  const ACTIONS = {
    home: () => location.href = getUrls().home,
    shop: () => location.href = getUrls().shop,

    cart: () => trigger('.cart-widget-opener a'),
    nav:  () => trigger('.wd-toolbar-link-2 a'),
    chat: () => trigger('.wd-toolbar-link-1 a') // placeholder
  };

  function getRoot() {
    return document.getElementById('gstore-floating-toolbar');
  }

  function getUrls() {
    const root = getRoot();
    return {
      home: root?.dataset.home || window.GSTORE_TOOLBAR?.home || '/',
      shop: root?.dataset.shop || window.GSTORE_TOOLBAR?.shop || '/shop/'
    };
  }

  document.addEventListener('click', e => {
    const btn = e.target.closest?.('.gstore-toolbar-btn');
    if (!btn) return;
    const root = getRoot();
    if (!root || !root.contains(btn)) return;
    ACTIONS[btn.dataset.action]?.();
  });

  function getCartElements() {
    const root = getRoot();
    if (!root) return {};
    const cartBtn = root.querySelector('[data-action="cart"]');
    return {
      cartBtn,
      cartBadge: cartBtn?.querySelector('.gstore-cart-badge'),
      cartToast: cartBtn?.querySelector('.gstore-cart-toast')
    };
  }

  function parseCount(text) {
    const match = String(text || '').match(/\d+/);
    return match ? parseInt(match[0], 10) : 0;
  }

  function getCartCountFromDom() {
    const selectors = [
      '[data-cart-count]',
      '.cart-widget-opener .wd-tools-count',
      '.cart-widget-opener .count',
      '.wd-tools-count',
      '.cart-contents .count',
      '.cart-contents-count',
      '.shopping-cart .count',
      '.mini-cart .count',
      '.widget_shopping_cart .count'
    ];

    for (const selector of selectors) {
      const el = document.querySelector(selector);
      if (!el) continue;
      if (el.hasAttribute('data-cart-count')) {
        return parseInt(el.getAttribute('data-cart-count'), 10) || 0;
      }
      const text = el.textContent || el.getAttribute('aria-label');
      const count = parseCount(text);
      if (count) return count;
    }

    return 0;
  }

  function setCartCount(count) {
    const { cartBtn, cartBadge } = getCartElements();
    if (!cartBtn || !cartBadge) return;
    const safeCount = Number.isFinite(count) ? Math.max(count, 0) : 0;
    cartBadge.textContent = safeCount > 99 ? '99+' : String(safeCount);
    cartBtn.classList.toggle('has-count', safeCount > 0);
  }

  function updateCartCount() {
    setCartCount(getCartCountFromDom());
  }

  function flashCartFeedback() {
    const { cartBtn, cartToast } = getCartElements();
    if (!cartBtn || !cartToast) return;
    cartBtn.classList.remove('is-bump', 'is-toast');
    void cartToast.offsetWidth;
    cartBtn.classList.add('is-bump', 'is-toast');
  }

  function trigger(selector) {
    const el = document.querySelector(selector);
    if (el) el.click();
  }

  /* Hide / show on scroll */
  let lastY = window.scrollY;
  window.addEventListener('scroll', () => {
    const root = getRoot();
    if (!root) return;
    const y = window.scrollY;
    root.classList.toggle('is-hidden', y > lastY && y > 80);
    lastY = y;
  });

  updateCartCount();
  setTimeout(updateCartCount, 50);
  setTimeout(updateCartCount, 250);
  setTimeout(updateCartCount, 1000);

  document.body?.addEventListener('added_to_cart', () => {
    setTimeout(updateCartCount, 150);
    flashCartFeedback();
  });
  document.body?.addEventListener('wc_fragments_refreshed', updateCartCount);

  if (window.MutationObserver) {
    let pending = false;
    const observer = new MutationObserver(() => {
      if (pending) return;
      pending = true;
      setTimeout(() => {
        pending = false;
        updateCartCount();
      }, 150);
    });
    observer.observe(document.body, { childList: true, subtree: true, characterData: true });
  }

})();
