import{r as i,h as t}from"./p-dfbe004d.js";import{_ as s}from"./p-8415f806.js";import"./p-fd56940f.js";import{U as o}from"./p-c7dd942d.js";import{c as r}from"./p-afcbd440.js";import{c as n}from"./p-85821e4e.js";import{g as e,s as a}from"./p-10aa7556.js";import{u as d}from"./p-57d82274.js";import"./p-9a7a47e8.js";import"./p-699b9e85.js";import"./p-ea78c070.js";import"./p-35c4916d.js";import"./p-a41f5fb3.js";import"./p-6c2a2148.js";import"./p-7393a06c.js";import"./p-1c2e2695.js";import"./p-4d73f82a.js";const l={expand:["line_items","line_item.price","price.product","customer","customer.shipping_address","payment_intent","discount","discount.promotion","discount.coupon","shipping_address","tax_identifier"]},p=class{constructor(t){i(this,t),this.quantity=1,this.mode="live"}getLineItem(){var i,t;const s=this.getOrder(),o=((null===(i=null==s?void 0:s.line_items)||void 0===i?void 0:i.data)||[]).find((i=>{var t;return(null===(t=i.price)||void 0===t?void 0:t.id)===this.priceId}));return!!(null==o?void 0:o.id)&&{id:null==o?void 0:o.id,price_id:null===(t=null==o?void 0:o.price)||void 0===t?void 0:t.id,quantity:null==o?void 0:o.quantity}}getOrder(){return e(null==this?void 0:this.formId,this.mode)}async addToCart(){const{price:i}=await this.form.getFormJson();try{this.busy=!0;const t=await this.addOrUpdateLineItem({...i?{ad_hoc_amount:parseInt(i)||null}:{}});a(t,this.formId),d.set("cart",{...d.state.cart,open:!0})}catch(i){console.error(i),this.error=(null==i?void 0:i.message)||s("Something went wrong","surecart")}finally{this.busy=!1}}async addOrUpdateLineItem(i={}){var t,s;let o=this.getLineItem(),e=r((null===(t=this.getOrder())||void 0===t?void 0:t.line_items)||[]);return await n({id:null===(s=this.getOrder())||void 0===s?void 0:s.id,data:{live_mode:"live"===this.mode,line_items:[...(e||[]).map((t=>this.priceId===(null==t?void 0:t.price_id)?{...t,...(null==i?void 0:i.ad_hoc_amount)?{ad_hoc_amount:null==i?void 0:i.ad_hoc_amount}:{},quantity:(null==t?void 0:t.ad_hoc_amount)?1:(null==t?void 0:t.quantity)+1}:t)),...o?[]:[{price_id:this.priceId,...(null==i?void 0:i.ad_hoc_amount)?{ad_hoc_amount:null==i?void 0:i.ad_hoc_amount}:{},quantity:1}]]},query:{...l,form_id:this.formId}})}componentWillLoad(){o.create(this,this.state())}state(){return{busy:this.busy,error:this.error,order:this.getOrder()}}render(){return t("sc-form",{ref:i=>this.form=i,onScSubmit:()=>{this.addToCart()}},this.error&&t("sc-alert",{open:!!this.error,type:"danger"},t("span",{slot:"title"},s("Error","surecart")),this.error),t(o.Provider,{state:this.state()},t("slot",null)))}};p.style="sc-cart-form { display: inline-block }";export{p as sc_cart_form}