{% comment %} Wishlist Go — Product Wishlist Embed (all product button settings live here) {% endcomment %}

<div
  id="wl-product-embed"
  data-button-style="{{ block.settings.button_style | escape }}"
  data-label-add="{{ block.settings.label_add | escape }}"
  data-label-added="{{ block.settings.label_added | escape }}"
  data-icon-color="{{ block.settings.icon_color }}"
  data-icon-hover-color="{{ block.settings.icon_hover_color }}"
  data-active-color="{{ block.settings.active_color }}"
  data-button-bg-color="{{ block.settings.button_bg_color }}"
  data-button-text-color="{{ block.settings.button_text_color }}"
  data-button-border-color="{{ block.settings.button_border_color }}"
  data-button-hover-bg-color="{{ block.settings.button_hover_bg_color }}"
  data-button-hover-text-color="{{ block.settings.button_hover_text_color }}"
  data-active-bg-color="{{ block.settings.active_bg_color }}"
  data-active-text-color="{{ block.settings.active_text_color }}"
  data-active-border-color="{{ block.settings.active_border_color }}"
  data-border-width="{{ block.settings.border_width }}"
  data-border-radius="{{ block.settings.border_radius }}"
  data-padding-top="{{ block.settings.padding_top }}"
  data-padding-right="{{ block.settings.padding_right }}"
  data-padding-bottom="{{ block.settings.padding_bottom }}"
  data-padding-left="{{ block.settings.padding_left }}"
  data-custom-selector-enabled="{{ block.settings.enable_custom_selector }}"
  data-custom-selector="{{ block.settings.custom_selector | escape }}"
  data-custom-selector-mode="{{ block.settings.custom_selector_mode | escape }}"
  style="display:none;"
></div>

<script>
(function () {

  var embedEl = document.getElementById('wl-product-embed');
  if (!embedEl) return;

  // ── Only run on product pages ─────────────────────────────────────────────
  if (!window.location.pathname.match(/^\/products\//)) return;

  // ── icon_style and stroke_width are centralised in the app-embed ──────────
  var rootEl      = document.getElementById('wl-root');
  var iconStyle   = (rootEl && rootEl.dataset.iconStyle)   || 'heart';
  var strokeWidth = (rootEl && rootEl.dataset.strokeWidth) || '2';

  // ── Read settings ─────────────────────────────────────────────────────────
  var buttonStyle          = embedEl.dataset.buttonStyle || 'inline';
  var labelAdd             = embedEl.dataset.labelAdd || 'Add to Wishlist';
  var labelAdded           = embedEl.dataset.labelAdded || 'Added to Wishlist';
  var iconColor            = embedEl.dataset.iconColor || '#111111';
  var iconHoverColor       = embedEl.dataset.iconHoverColor || '#333333';
  var activeColor          = embedEl.dataset.activeColor || '#e53e3e';
  var buttonBgColor        = embedEl.dataset.buttonBgColor || '#ffffff';
  var buttonTextColor      = embedEl.dataset.buttonTextColor || '#111111';
  var buttonBorderColor    = embedEl.dataset.buttonBorderColor || '#111111';
  var buttonHoverBgColor   = embedEl.dataset.buttonHoverBgColor || '#111111';
  var buttonHoverTextColor = embedEl.dataset.buttonHoverTextColor || '#ffffff';
  var activeBgColor        = embedEl.dataset.activeBgColor || '#fff0f0';
  var activeTextColor      = embedEl.dataset.activeTextColor || '#e53e3e';
  var activeBorderColor    = embedEl.dataset.activeBorderColor || '#e53e3e';
  var borderWidth          = embedEl.dataset.borderWidth || '2';
  var borderRadius         = embedEl.dataset.borderRadius || '4';
  var paddingTop           = embedEl.dataset.paddingTop || '0';
  var paddingRight         = embedEl.dataset.paddingRight || '0';
  var paddingBottom        = embedEl.dataset.paddingBottom || '0';
  var paddingLeft          = embedEl.dataset.paddingLeft || '0';
  var customSelectorEnabled = embedEl.dataset.customSelectorEnabled === 'true';
  var customSelector       = embedEl.dataset.customSelector || '';
  var customSelectorMode   = embedEl.dataset.customSelectorMode || 'event_only';

  var isFull = buttonStyle === 'full';

  // ── SVG icons ─────────────────────────────────────────────────────────────
  var HEART_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"'
    + ' stroke="currentColor" stroke-width="' + strokeWidth + '" stroke-linecap="round" stroke-linejoin="round"'
    + ' width="20" height="20" aria-hidden="true" focusable="false">'
    + '<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>'
    + '</svg>';

  var BOOKMARK_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"'
    + ' stroke="currentColor" stroke-width="' + strokeWidth + '" stroke-linecap="round" stroke-linejoin="round"'
    + ' width="20" height="20" aria-hidden="true" focusable="false">'
    + '<path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/>'
    + '</svg>';

  var iconSVG = iconStyle === 'bookmark' ? BOOKMARK_SVG : HEART_SVG;

  // ── Product handle resolver ───────────────────────────────────────────────
  function resolveHandle() {
    try {
      var h = window.ShopifyAnalytics && window.ShopifyAnalytics.meta
               && window.ShopifyAnalytics.meta.product
               && window.ShopifyAnalytics.meta.product.handle;
      if (h) return h;
    } catch (_) {}

    try {
      var match = window.location.pathname.match(/\/products\/([^/?#]+)/);
      if (match && match[1]) return match[1];
    } catch (_) {}

    try {
      var form = document.querySelector('form[action*="/cart/add"]');
      if (form && form.dataset.productHandle) return form.dataset.productHandle;
    } catch (_) {}

    console.warn('[Wishlist] Could not resolve product handle on this page.');
    return null;
  }

  // ── Apply styles to button ────────────────────────────────────────────────
  function applyStyles(btn) {
    if (isFull) {
      btn.style.cssText = [
        'display:flex', 'align-items:center', 'justify-content:center',
        'gap:8px', 'width:100%', 'cursor:pointer',
        'padding:' + paddingTop + 'px ' + paddingRight + 'px ' + paddingBottom + 'px ' + paddingLeft + 'px',
        'border:' + borderWidth + 'px solid ' + buttonBorderColor,
        'border-radius:' + borderRadius + 'px',
        'background:' + buttonBgColor,
        'color:' + buttonTextColor,
        'font-size:inherit', 'font-weight:inherit',
        'transition:background 0.15s ease,color 0.15s ease,border-color 0.15s ease'
      ].join(';');
      btn.addEventListener('mouseenter', function () {
        if (!btn.classList.contains('wl-product-btn--active')) {
          btn.style.background = buttonHoverBgColor;
          btn.style.color = buttonHoverTextColor;
        }
      });
      btn.addEventListener('mouseleave', function () {
        if (!btn.classList.contains('wl-product-btn--active')) {
          btn.style.background = buttonBgColor;
          btn.style.color = buttonTextColor;
        }
      });
    } else {
      btn.style.cssText = [
        'display:inline-flex', 'align-items:center', 'gap:8px',
        'background:none', 'border:none', 'cursor:pointer',
        'padding:' + paddingTop + 'px ' + paddingRight + 'px ' + paddingBottom + 'px ' + paddingLeft + 'px',
        'color:' + iconColor, 'font-size:inherit', 'font-weight:inherit',
        'transition:color 0.15s ease'
      ].join(';');
      btn.addEventListener('mouseenter', function () {
        if (!btn.classList.contains('wl-product-btn--active')) btn.style.color = iconHoverColor;
      });
      btn.addEventListener('mouseleave', function () {
        if (!btn.classList.contains('wl-product-btn--active')) btn.style.color = iconColor;
      });
    }
  }

  // ── Build the injected button ─────────────────────────────────────────────
  function buildButton(handle) {
    var btn = document.createElement('button');
    btn.className  = 'wl-product-btn wl-product-btn--' + buttonStyle;
    btn.dataset.handle = handle;
    btn.setAttribute('aria-label', 'Add to wishlist');
    btn.setAttribute('aria-pressed', 'false');
    btn.innerHTML = '<span class="wl-product-btn__icon">' + iconSVG + '</span>'
      + '<span class="wl-product-btn__text">' + labelAdd + '</span>';
    applyStyles(btn);
    return btn;
  }

  // ── Sync button state ─────────────────────────────────────────────────────
  function syncState(btn, handle) {
    if (!window.Wishlist) return;
    var inList = window.Wishlist.hasByHandle(handle);
    var textEl = btn.querySelector('.wl-product-btn__text');
    var svg    = btn.querySelector('svg');

    btn.classList.toggle('wl-product-btn--active', inList);
    btn.setAttribute('aria-pressed', String(inList));
    btn.setAttribute('aria-label', inList ? 'Remove from wishlist' : 'Add to wishlist');
    if (textEl) textEl.textContent = inList ? labelAdded : labelAdd;
    if (svg)    svg.setAttribute('fill', inList ? 'currentColor' : 'none');

    if (isFull) {
      btn.style.background   = inList ? activeBgColor    : buttonBgColor;
      btn.style.color        = inList ? activeTextColor  : buttonTextColor;
      btn.style.borderColor  = inList ? activeBorderColor : buttonBorderColor;
    } else {
      btn.style.color = inList ? activeColor : iconColor;
    }
  }

  // ── Wire up button events ─────────────────────────────────────────────────
  function wireButton(btn, handle) {
    btn.addEventListener('click', async function () {
      if (!window.Wishlist) return;
      btn.classList.add('wl-product-btn--loading');
      btn.style.opacity = '0.6';
      btn.style.pointerEvents = 'none';
      try {
        await window.Wishlist.toggle(handle);
        syncState(btn, handle);
      } catch (err) {
        console.error('[Wishlist] Product embed toggle failed:', err);
      } finally {
        btn.classList.remove('wl-product-btn--loading');
        btn.style.opacity = '';
        btn.style.pointerEvents = '';
      }
    });
    document.addEventListener('wishlist:add',    function () { syncState(btn, handle); });
    document.addEventListener('wishlist:remove', function () { syncState(btn, handle); });
    document.addEventListener('wishlist:sync',   function () { syncState(btn, handle); });
  }

  // ── Custom selector handling ──────────────────────────────────────────────
  function handleCustomSelector() {
    if (!customSelectorEnabled || !customSelector) return;
    if (document.querySelector('.wl-product-btn')) return;

    var handle = resolveHandle();
    if (!handle) return;

    var target = document.querySelector(customSelector);
    if (!target) {
      console.warn('[Wishlist] Product embed: custom selector "' + customSelector + '" not found.');
      return;
    }

    if (customSelectorMode === 'inject_button') {
      var btn = buildButton(handle);
      target.appendChild(btn);
      syncState(btn, handle);
      wireButton(btn, handle);
      console.log('[Wishlist] Product wishlist button injected into "' + customSelector + '"');
    } else {
      target.addEventListener('click', async function () {
        if (!window.Wishlist) return;
        await window.Wishlist.toggle(handle);
      });
      console.log('[Wishlist] Wishlist toggle event attached to "' + customSelector + '"');
    }
  }

  // ── Init ──────────────────────────────────────────────────────────────────
  function init() {
    handleCustomSelector();
  }

  if (window.Wishlist) {
    init();
  } else {
    document.addEventListener('DOMContentLoaded', init);
  }

})();
</script>

{% schema %}
{
  "name": "WishlistGo Product Button",
  "target": "body",
  "settings": [
    {
      "type": "checkbox",
      "id": "enable_custom_selector",
      "label": "Enable custom selector",
      "default": false,
      "info": "Use this for themes that don't support blocks in the product section. Enter a CSS selector to target your product form area."
    },
    {
      "type": "text",
      "id": "custom_selector",
      "label": "CSS selector",
      "placeholder": ".product-form__buttons, .product__buttons",
      "info": "The CSS selector of the element in your product section to target.",
      "visible_if": "{{ block.settings.enable_custom_selector == true }}"
    },
    {
      "type": "select",
      "id": "custom_selector_mode",
      "label": "Mode",
      "options": [
        { "value": "event_only",    "label": "Event only (attach toggle to existing element)" },
        { "value": "inject_button", "label": "Inject wishlist button into element" }
      ],
      "default": "inject_button",
      "visible_if": "{{ block.settings.enable_custom_selector == true }}"
    },
    {
      "type": "paragraph",
      "content": "Event only: clicking their element toggles the wishlist.",
      "visible_if": "{{ block.settings.enable_custom_selector == true and block.settings.custom_selector_mode == 'event_only' }}"
    },
    {
      "type": "paragraph",
      "content": "Inject: our button is added inside the selected element.",
      "visible_if": "{{ block.settings.enable_custom_selector == true and block.settings.custom_selector_mode == 'inject_button' }}"
    },
    {
      "type": "select",
      "id": "button_style",
      "label": "Button style",
      "options": [
        { "value": "inline", "label": "Icon + Text (inline)" },
        { "value": "full",   "label": "Full width button" }
      ],
      "default": "inline"
    },
    {
      "type": "text",
      "id": "label_add",
      "label": "Add to wishlist label",
      "default": "Add to Wishlist"
    },
    {
      "type": "text",
      "id": "label_added",
      "label": "Added to wishlist label",
      "default": "Added to Wishlist"
    },
    {
      "type": "header",
      "content": "Colors"
    },
    {
      "type": "color",
      "id": "icon_color",
      "label": "Icon color",
      "default": "#111111",
      "visible_if": "{{ block.settings.button_style == 'inline' }}"
    },
    {
      "type": "color",
      "id": "icon_hover_color",
      "label": "Icon hover color",
      "default": "#333333",
      "visible_if": "{{ block.settings.button_style == 'inline' }}"
    },
    {
      "type": "color",
      "id": "active_color",
      "label": "Active color",
      "default": "#e53e3e",
      "visible_if": "{{ block.settings.button_style == 'inline' }}"
    },
    {
      "type": "color",
      "id": "button_bg_color",
      "label": "Button background",
      "default": "#ffffff",
      "visible_if": "{{ block.settings.button_style == 'full' }}"
    },
    {
      "type": "color",
      "id": "button_text_color",
      "label": "Button text color",
      "default": "#111111",
      "visible_if": "{{ block.settings.button_style == 'full' }}"
    },
    {
      "type": "color",
      "id": "button_border_color",
      "label": "Button border color",
      "default": "#111111",
      "visible_if": "{{ block.settings.button_style == 'full' }}"
    },
    {
      "type": "color",
      "id": "button_hover_bg_color",
      "label": "Button hover background",
      "default": "#111111",
      "visible_if": "{{ block.settings.button_style == 'full' }}"
    },
    {
      "type": "color",
      "id": "button_hover_text_color",
      "label": "Button hover text color",
      "default": "#ffffff",
      "visible_if": "{{ block.settings.button_style == 'full' }}"
    },
    {
      "type": "color",
      "id": "active_bg_color",
      "label": "Active background",
      "default": "#fff0f0",
      "visible_if": "{{ block.settings.button_style == 'full' }}"
    },
    {
      "type": "color",
      "id": "active_text_color",
      "label": "Active text color",
      "default": "#e53e3e",
      "visible_if": "{{ block.settings.button_style == 'full' }}"
    },
    {
      "type": "color",
      "id": "active_border_color",
      "label": "Active border color",
      "default": "#e53e3e",
      "visible_if": "{{ block.settings.button_style == 'full' }}"
    },
    {
      "type": "header",
      "content": "Border"
    },
    {
      "type": "range",
      "id": "border_width",
      "label": "Border width",
      "min": 0,
      "max": 10,
      "step": 1,
      "default": 2,
      "unit": "px"
    },
    {
      "type": "range",
      "id": "border_radius",
      "label": "Border radius",
      "min": 0,
      "max": 40,
      "step": 2,
      "default": 4,
      "unit": "px"
    },
    {
      "type": "header",
      "content": "Spacing"
    },
    {
      "type": "range",
      "id": "padding_top",
      "label": "Padding top",
      "min": 0,
      "max": 40,
      "step": 2,
      "default": 0,
      "unit": "px"
    },
    {
      "type": "range",
      "id": "padding_right",
      "label": "Padding right",
      "min": 0,
      "max": 40,
      "step": 2,
      "default": 0,
      "unit": "px"
    },
    {
      "type": "range",
      "id": "padding_bottom",
      "label": "Padding bottom",
      "min": 0,
      "max": 40,
      "step": 2,
      "default": 0,
      "unit": "px"
    },
    {
      "type": "range",
      "id": "padding_left",
      "label": "Padding left",
      "min": 0,
      "max": 40,
      "step": 2,
      "default": 0,
      "unit": "px"
    }
  ]
}
{% endschema %}
