/** Shopify CDN: Minification failed

Line 24:0 Unexpected "("
Line 85:70 Unterminated string token
Line 102:4 Comments in CSS use "/* ... */" instead of "//"
Line 107:8 Comments in CSS use "/* ... */" instead of "//"
Line 112:4 Comments in CSS use "/* ... */" instead of "//"
Line 120:27 Comments in CSS use "/* ... */" instead of "//"
Line 124:4 Comments in CSS use "/* ... */" instead of "//"
Line 134:4 Comments in CSS use "/* ... */" instead of "//"
Line 134:62 Unterminated string token
Line 135:4 Comments in CSS use "/* ... */" instead of "//"
... and 1 more hidden warnings

**/
/*
  Belantti Wishlist v6.0 (Visible-Wrapper Icon Fix)
  Fix:
  - Wishlist logic unchanged
  - Icon is applied to the FIRST VISIBLE WRAPPER (real width/height)
  - Survives font-size:0, svg hidden, overflow masks, empty inner elements
*/

(function () {
  const WISHLIST_KEY = 'belantti_wishlist';

  /* ===============================
     STORAGE
  =============================== */

  window.getWishlist = function () {
    try {
      return JSON.parse(localStorage.getItem(WISHLIST_KEY)) || [];
    } catch (e) {
      return [];
    }
  };

  const saveWishlist = function (list) {
    localStorage.setItem(WISHLIST_KEY, JSON.stringify(list));
    updateIcons();
    updateHeaderBadge();
  };

  /* ===============================
     TOAST
  =============================== */

  const toast = function (msg) {
    const existing = document.querySelector('.wishlist-toast');
    if (existing) existing.remove();

    const el = document.createElement('div');
    el.className = 'wishlist-toast';
    el.textContent = msg;

    Object.assign(el.style, {
      position: 'fixed',
      bottom: '40px',
      left: '50%',
      transform: 'translateX(-50%)',
      background: '#000',
      color: '#fff',
      padding: '12px 30px',
      fontSize: '11px',
      letterSpacing: '2px',
      textTransform: 'uppercase',
      zIndex: '2147483647',
      transition: 'opacity 0.4s ease'
    });

    document.body.appendChild(el);
    setTimeout(() => {
      el.style.opacity = '0';
      setTimeout(() => el.remove(), 400);
    }, 2000);
  };

  /* ===============================
     ICON (SVG DATA URI)
  =============================== */

  const svgToDataUri = (svg) =>
    'data:image/svg+xml;charset=UTF-8,' +
    encodeURIComponent(svg).replace(/'/g, '%27').replace(/"/g, '%22');

  const HEART_OUTLINE_SVG = (stroke) => `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
      <path d="M12 21s-6.7-4.35-9.5-7.3C-1.5 9.2 1.2 3 6.5 3c2.1 0 3.4 1.1 4.5 2.3C12.1 4.1 13.4 3 15.5 3 20.8 3 23.5 9.2 21.5 13.7 18.7 16.65 12 21 12 21z"
            fill="none" stroke="${stroke}" stroke-width="2" stroke-linejoin="round"/>
    </svg>
  `.trim();

  const HEART_FILLED_SVG = (fill) => `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
      <path d="M12 21s-6.7-4.35-9.5-7.3C-1.5 9.2 1.2 3 6.5 3c2.1 0 3.4 1.1 4.5 2.3C12.1 4.1 13.4 3 15.5 3 20.8 3 23.5 9.2 21.5 13.7 18.7 16.65 12 21 12 21z"
            fill="${fill}"/>
    </svg>
  `.trim();

  const getFirstVisibleWrapper = (el) => {
    // Walk up: find first element that actually has clickable-icon dimensions
    let node = el;
    for (let i = 0; i < 8 && node; i++) {
      if (node instanceof HTMLElement) {
        const r = node.getBoundingClientRect();
        // Typical icon button is ~28–44px square; accept anything reasonably sized
        if (r.width >= 22 && r.height >= 22) return node;
      }
      node = node.parentElement;
    }
    // Fallback: apply to element itself
    return el instanceof HTMLElement ? el : null;
  };

  const applyHeartIcon = (btn, isActive) => {
    const target = getFirstVisibleWrapper(btn);
    if (!target) return;

    const colour = '#111'; // change to '#C9A46A' if you want gold
    const svg = isActive ? HEART_FILLED_SVG(colour) : HEART_OUTLINE_SVG(colour);
    const uri = svgToDataUri(svg);

    // Apply inline background icon to the visible wrapper (NOT the hidden inner element)
    target.dataset.belWishlistIcon = '1';

    Object.assign(target.style, {
      backgroundImage: `url("${uri}")`,
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'center',
      backgroundSize: '18px 18px'
    });

    // Ensure any child icon content can't override visibility
    // (Some themes insert empty <i> that can sit on top)
    Array.from(target.children).forEach((child) => {
      if (!(child instanceof HTMLElement)) return;
      if (child.classList.contains('wishlist-heart') || child.classList.contains('bel-heart')) return;
    });
  };

  /* ===============================
     ICON STATE
  =============================== */

  const updateIcons = function () {
    const list = window.getWishlist();

    document.querySelectorAll('.engoj_add_to_wishlist').forEach(btn => {
      const handle = btn.getAttribute('data-handle');
      if (!handle) return;

      const isActive = list.some(i => i.handle === handle);
      btn.classList.toggle('active', isActive);

      applyHeartIcon(btn, isActive);
    });
  };

  /* ===============================
     HEADER BADGE
  =============================== */

  const updateHeaderBadge = function () {
    const list = window.getWishlist();
    const count = list.length;

    const links = document.querySelectorAll('a[href*="wishlist"]');
    if (!links.length) return;

    links.forEach(link => {
      let badge = link.querySelector('.wishlist-badge');

      if (count === 0) {
        if (badge) badge.remove();
        return;
      }

      if (!badge) {
        badge = document.createElement('span');
        badge.className = 'wishlist-badge';
        link.style.position = 'relative';
        link.appendChild(badge);
      }

      badge.textContent = count;

      Object.assign(badge.style, {
        position: 'absolute',
        top: '-5px',
        right: '-8px',
        background: '#000',
        color: '#fff',
        fontSize: '9px',
        fontWeight: '700',
        width: '16px',
        height: '16px',
        borderRadius: '50%',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        border: '1px solid #fff',
        zIndex: '10'
      });
    });
  };

  /* ===============================
     CLICK HANDLING
  =============================== */

  document.addEventListener('click', function (e) {
    const btn = e.target.closest('.engoj_add_to_wishlist');
    if (!btn) return;

    e.preventDefault();
    e.stopPropagation();

    const handle = btn.getAttribute('data-handle');
    if (!handle) return;

    const product = {
      handle,
      title: btn.getAttribute('data-title') || '',
      image: btn.getAttribute('data-image') || '',
      price: btn.getAttribute('data-price') || '',
      url: btn.getAttribute('data-url') || '#'
    };

    let list = window.getWishlist();
    const index = list.findIndex(i => i.handle === handle);

    if (index > -1) {
      list.splice(index, 1);
      toast('Removed from Wishlist');
    } else {
      list.push(product);
      toast('Added to Wishlist');
    }

    saveWishlist(list);
  }, true);

  /* ===============================
     INIT
  =============================== */

  const init = function () {
    updateIcons();
    updateHeaderBadge();

    const observer = new MutationObserver(() => {
      updateIcons();
      updateHeaderBadge();
    });
    observer.observe(document.body, { childList: true, subtree: true });
  };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();
