/* global Packeta */

function zasilkovnaWidget(deliveryId, APIkey, options = undefined) {
   function selectPickupPoint(point) {
      if (point) {
         $('#dzl_' + deliveryId).val(JSON.stringify(point)).trigger('change');
      }
   }

   if (typeof options === 'undefined') {
      options = {};
   }

   $('#cart').on('cartdeliverychange', function(e, data) {
      const inputValue = JSON.parse($('#dzl_' + deliveryId).val());

      if (parseInt(data.delivery_id) === deliveryId && inputValue.name === 'Neznámá pobočka') {
         setTimeout(function() {
            Packeta.Widget.pick(APIkey, selectPickupPoint, {...options});
         }, 100);
      }
   });

   $(`[data-zasilkovna-wrapper-${deliveryId}]`).on('click', '[data-btn="open-packeta-widget"]', function() {
      Packeta.Widget.pick(APIkey, selectPickupPoint, {...options});
      return false;
   });
}
