import state,{on}from"./store";import{setProduct}from"./setters";import{getVariantFromValues}from"../../functions/util";import{isStockNeedsToBeChecked}from"./getters";import{speak}from"@wordpress/a11y";import{__,sprintf}from"@wordpress/i18n";on("set",((t,e,i)=>{var a,d,o,l;(null===(a=null==e?void 0:e.selectedPrice)||void 0===a?void 0:a.id)!==(null===(d=null==i?void 0:i.selectedPrice)||void 0===d?void 0:d.id)&&updateSelectedPrice(t,e),(null===(o=null==e?void 0:e.selectedVariant)||void 0===o?void 0:o.id)!==(null===(l=null==i?void 0:i.selectedVariant)||void 0===l?void 0:l.id)&&handleStockWithSelectedVariant(t),(!i||["selectedPrice","adHocAmount","quantity","selectedVariant"].some((t=>JSON.stringify(e[t])!==JSON.stringify(i[t]))))&&setLineItem(t),(!i||JSON.stringify(null==e?void 0:e.variantValues)!==JSON.stringify(null==i?void 0:i.variantValues))&&updateSelectedVariant(t,e)}));const updateSelectedVariant=(t,e)=>{const i=getVariantFromValues({variants:state[t].variants,values:null==e?void 0:e.variantValues});i&&setProduct(t,{selectedVariant:i})},handleStockWithSelectedVariant=t=>{var e,i,a;state[t].selectedVariant&&isStockNeedsToBeChecked(t)&&(null===(e=state[t])||void 0===e?void 0:e.selectedVariant.available_stock)<(null===(i=state[t])||void 0===i?void 0:i.quantity)&&(state[t].quantity=(null===(a=state[t])||void 0===a?void 0:a.selectedVariant.available_stock)||1,speak(sprintf(__("There are just %d items left in stock, and the quantity has been adjusted to %d.","surecart"),state[t].quantity,state[t].quantity),"assertive"))},updateSelectedPrice=(t,e)=>{var i,a,d,o;setProduct(t,{total:state[t].adHocAmount||(null===(i=null==e?void 0:e.selectedPrice)||void 0===i?void 0:i.amount)||0,adHocAmount:null===(a=null==e?void 0:e.selectedPrice)||void 0===a?void 0:a.amount,disabled:(null===(d=null==e?void 0:e.selectedPrice)||void 0===d?void 0:d.archived)||(null===(o=state[t].product)||void 0===o?void 0:o.archived)})};"undefined"!=typeof document&&document.addEventListener("scVariantValuesUpdated",(t=>{const{productId:e,variantValues:i}=t.detail||{};e&&state[e]&&i&&setProduct(e,{variantValues:i})}));const setLineItem=t=>{var e,i,a,d,o,l,n,s;setProduct(t,{line_item:{price_id:null===(i=null===(e=state[t])||void 0===e?void 0:e.selectedPrice)||void 0===i?void 0:i.id,quantity:Math.max((null===(d=null===(a=state[t])||void 0===a?void 0:a.selectedPrice)||void 0===d?void 0:d.ad_hoc)?1:state[t].quantity,1),...(null===(l=null===(o=state[t])||void 0===o?void 0:o.selectedPrice)||void 0===l?void 0:l.ad_hoc)?{ad_hoc_amount:null===(n=state[t])||void 0===n?void 0:n.adHocAmount}:{},variant_id:null===(s=state[t].selectedVariant)||void 0===s?void 0:s.id}})};