import{useQuantity as t,useCurrentVariantInStock as e,useProduct as r,useIsSyncProduct as a,useInteraction as n}from"@gem-sdk/core";import{useRef as u,useEffect as o}from"react";import{useTransition as i}from"../../product-variants/common/common.js";let useProductQuantity=d=>{let{setting:l={},advanced:c}=d,{updatePrice:m}=l,{quantity:s,setQuantity:p,setUpdatePrice:y,increment:g,decrement:q}=t(),v=e(),f=r(),w=a(),{trigger:Q}=n(),$=u(null),b=l.defaultQtyValue||1;o(()=>{p(parseFloat(`${b}`))},[p,b]),o(()=>{y(m||!1)},[m,y]);let h=t=>{let e=t.detail,r=f?.id;w&&e&&r==e.productId&&s!=e.quantity&&(k(e.quantity),p(e.quantity))};o(()=>{window.removeEventListener("set-product-quantity",h),window.addEventListener("set-product-quantity",h)}),i(t=>{t!==s&&k(s||0)},[s]);let k=t=>{Q({event:"gp:rollback:quantity-change",selector:`[data-id="${c?.uid}"]`,element:$.current}),Q({event:"gp:quantity-change",selector:`[data-id="${c?.uid}"]`,data:t,element:$.current})},E=()=>{v&&g()},I=()=>{v&&q()},L=t=>{v&&p(parseInt(t.target.value,10))},P=t=>{v||t.target.blur()};return{isInStock:v,ref:$,onClickIncrement:E,onClickDecrement:I,onChangeInput:L,onFocusInput:P}};export{useProductQuantity};
