import{useRenderMode as e,useProduct as t,useCurrency as r,useQuantity as i,useProductProperties as s,useCurrentVariant as n,useHasPreSelected as o,useStickyStore as a,useProductStore as u,useCreateCart as l,useAddToCart as c,convertDecimalToNumber as m,useCurrentVariantInStock as b}from"@gem-sdk/core";import{useRef as f,useEffect as p,useCallback as d}from"react";import{addToCartTracking as v}from"../../../helpers/tracking.js";import{useDispatchInteractionEvent as g,useDispatchCustomEvent as I}from"./useDispatchAfterSubmitEvent.js";import{useCartMessage as k}from"./useCartMessage.js";import{useCartOperations as D}from"./useCartOperations.js";let S=({styles:S,setting:E,builderProps:h})=>{let j=f(null),{isEditMode:y,isPreviewSharePageMode:C}=e(),M=t(),{currency:O}=r(),{quantity:w}=i(),A=s(),L=n(),{hasPreSelected:q}=o(),x=a(e=>e.setStickyVisible),B=u(e=>e.updateIsSubmit),T=g(h?.uid),U=I({product:M,currentVariant:L,quantity:w}),{showMessage:V,notiComponent:z}=k(S,E),{handleSuccess:F,handleError:G,cartId:H}=D({setting:E,showMessage:V,dispatchInteractionEvent:T,dispatchCustomEvent:U}),{isMutating:J,trigger:K}=l({onSuccess:F,onError:G}),{isMutating:N,trigger:P}=c({onSuccess:F,onError:G});p(()=>{let e=new IntersectionObserver(e=>{let t=e[0];x(t?.isIntersecting)},{threshold:.1}),t=j.current;return j.current&&e.observe(j.current),()=>{t&&e.unobserve(t)}},[x]);let Q=d(()=>{if(!L?.baseID||!w||!M?.baseID||void 0!==q&&!q||y||C)return;let e=A?.some(e=>e.required&&!e.value);if(B(!0),e)return;let t=A?.filter(e=>!!e.value)?.map(e=>({key:e.key,value:e.value}));v({quantity:w,currency:O,id:M?.baseID,name:M?.title,brand:M?.vendor,sku:L.sku,price:m(L?.price),variant:L.title});let r={quantity:w,attributes:t,variantId:L.baseID};E?.actionEffect!=="buy-now"&&H?P({cartId:H,lines:[r]}):K({items:[r]})},[y,C,H,O,w,A,q,M?.title,M?.vendor,M?.baseID,L?.sku,L?.price,L?.title,L?.baseID,E?.actionEffect,K,P,B]),R=b(),W=L?E?.outOfStockLabel:"Unavailable";return{addToCartRef:j,isLoading:J||N,isInStock:R,notiComponent:z,outOfStockLabel:W,addToCart:Q}};export{S as useBtnAddToCart};
