define(['jquery','mage/url','Amasty_GA4/js/datalayer-storage','domReady!'],function($,urlBuilder,datalayerStorage){'use strict';$.widget('amGa4.wishlist',{options:{eventDataEndpoint:'amga4/event/track',gaEvent:{addToWishlist:'add_to_wishlist',addToCart:'add_to_cart'},storageKey:{wishlist:'amga4-wishlist',addToCart:'amga4-add-to-cart'}},selectors:{addToWishlistButton:'[data-action="add-to-wishlist"]',addToCartButton:'#wishlist-sidebar button.tocart, .wishlist-index-index .product-items button.tocart'},_create:function(){this.bindClickEvents();this.processAddToWishlistStorage();this.processAddToCartStorage();},bindClickEvents:function(){$(this.selectors.addToWishlistButton).on('click',(event)=>{this.storeNodeData($(event.target).closest(this.selectors.addToWishlistButton).data(),this.options.gaEvent.addToWishlist,this.options.storageKey.wishlist);});$(this.selectors.addToCartButton).on('click',(event)=>{const data=$(event.target).closest(this.selectors.addToCartButton).data();const productId=this.getProductId(event.target);productId&&!!data?.post?.data&&(data.post.data.product=productId);this.storeNodeData(data,this.options.gaEvent.addToCart,this.options.storageKey.addToCart);});},storeNodeData:function(data,gaEventName,storageKey){let dataToCollect={...data?.post?.data??data?.postNewWishlist?.data??{}};if(Object.keys(dataToCollect).length===0){return;} dataToCollect.event=gaEventName;datalayerStorage.pushItem(storageKey,dataToCollect);},processAddToWishlistStorage:function(){const shouldPerformRequest=(dataToCollect)=>{return dataToCollect?.wishlist_id!==undefined||(!!dataToCollect&&window.location.href===document.referrer);};this.processStorageData(this.options.storageKey.wishlist,this.setAdditionalWishlistData.bind(this),shouldPerformRequest);},processAddToCartStorage:function(){const shouldPerformRequest=(dataToCollect)=>{return!!dataToCollect&&window.location.href===document.referrer;} this.processStorageData(this.options.storageKey.addToCart,(dataToCollect)=>{},shouldPerformRequest);},processStorageData:function(storageKey,additionalDataSetter,shouldPerformRequest){const dataToCollect=datalayerStorage.getItem(storageKey);dataToCollect&&additionalDataSetter(dataToCollect);if(!shouldPerformRequest(dataToCollect)){return;} $.ajax({method:'POST',url:urlBuilder.build(this.options.eventDataEndpoint),data:dataToCollect,beforeSend:()=>{datalayerStorage.removeItem(storageKey);},success:(observedData)=>{observedData.forEach(data=>this.pushToDataLayer(data));}});},pushToDataLayer:function(eventData){window.dataLayer.push(eventData);},getWishlistId:function(){return window.location.pathname.match(/wishlist_id\/(\d+)/)?.[1]??undefined;},setAdditionalWishlistData:function(dataToCollect){dataToCollect.wishlist_id=dataToCollect.wishlist_id??this.getWishlistId();},getProductId:function(addToCartButton){return $(addToCartButton).closest('.product-item')?.find('[data-product-id]')?.data('product-id');}});return $.amGa4.wishlist;});