var Wick = Wick || {};

Wick.addToAnyCustomisation = {
  init: function () {
    const a2a_config = window.a2a_config || {};
    a2a_config.callbacks = a2a_config.callbacks || [];
    a2a_config.callbacks.push({
      share: this.addToAnyOnShare
    });
    window.a2a_config = a2a_config;
  },

  addToAnyOnShare: function (data) {
    if (data.service === 'Pinterest' && !!Wick.addToAnyCustomisation.getCurrentImage()) {
      window.open(Wick.addToAnyCustomisation.buildPinUrl(), '_blank');
      return {
        stop: true
      };
    }
    if (data.service === 'X' || data.service === 'Facebook' || data.service === 'WhatsApp') {
      window.open(data.node.href, '_blank');
      return {
        stop: true
      };
    }
  },

  buildPinUrl: function () {
    var pinImage = Wick.addToAnyCustomisation.getCurrentImage();
    var productName = Wick.addToAnyCustomisation.getProductName();
    return 'https://www.pinterest.com/pin/create/button/?url=' + window.location + '&media=' + encodeURIComponent(pinImage) + '&description=' + encodeURIComponent(productName);
  },

  getCurrentImage: function () {
    let url = Wick.addToAnyCustomisation.imageUrl || '';
    if (url.startsWith('/medias/')) {
      url = window.location.origin + url;
    }
    return url;
  },

  getProductName: function () {
    return $('.pdp__heading').text();
  }

};

Wick.addToAnyCustomisation.init();
