import { r as registerInstance, h } from './index-f1d2a96f.js';
import { _ as __ } from './default-i18n-91ef32a0.js';
import './index-0a61debd.js';
import { U as Universe } from './universe-3b85f034.js';
import { c as convertLineItemsToLineItemData } from './index-df9110d6.js';
import { c as createOrUpdateOrder } from './index-78c1ff29.js';
import { g as getOrder, s as setOrder } from './checkouts-d9b4e12a.js';
import { u as uiStore } from './ui-8d4378ed.js';
import './_commonjsHelpers-9943807e.js';
import './fetch-c0c608db.js';
import './add-query-args-f4c5962b.js';

const query = {
  expand: [
    'line_items',
    'line_item.price',
    'price.product',
    'customer',
    'customer.shipping_address',
    'payment_intent',
    'discount',
    'discount.promotion',
    'discount.coupon',
    'shipping_address',
    'tax_identifier',
  ],
};
const ScCartForm = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    /** The quantity */
    this.quantity = 1;
    /** Are we in test or live mode. */
    this.mode = 'live';
  }
  /** Find a line item with this price. */
  getLineItem() {
    var _a, _b;
    const order = this.getOrder();
    const lineItem = (((_a = order === null || order === void 0 ? void 0 : order.line_items) === null || _a === void 0 ? void 0 : _a.data) || []).find(item => { var _a; return ((_a = item.price) === null || _a === void 0 ? void 0 : _a.id) === this.priceId; });
    if (!(lineItem === null || lineItem === void 0 ? void 0 : lineItem.id)) {
      return {
        price_id: this.priceId,
        quantity: 0,
      };
    }
    return {
      id: lineItem === null || lineItem === void 0 ? void 0 : lineItem.id,
      price_id: (_b = lineItem === null || lineItem === void 0 ? void 0 : lineItem.price) === null || _b === void 0 ? void 0 : _b.id,
      quantity: lineItem === null || lineItem === void 0 ? void 0 : lineItem.quantity,
    };
  }
  getOrder() {
    return getOrder(this === null || this === void 0 ? void 0 : this.formId, this.mode);
  }
  /** Add the item to cart. */
  async addToCart() {
    const { price } = await this.form.getFormJson();
    try {
      this.busy = true;
      // if it's ad_hoc, update the amount. Otherwise increment the quantity.
      const order = await this.addOrUpdateLineItem({ ad_hoc_amount: parseInt(price) || null });
      // store the checkout in localstorage and open the cart
      setOrder(order, this.formId);
      uiStore.set('cart', { ...uiStore.state.cart, ...{ open: true } });
    }
    catch (e) {
      console.error(e);
      this.error = (e === null || e === void 0 ? void 0 : e.message) || __('Something went wrong', 'surecart');
    }
    finally {
      this.busy = false;
    }
  }
  async addOrUpdateLineItem(data = { ad_hoc_amount: null }) {
    var _a, _b;
    // get the current line item from the price id.
    let lineItem = this.getLineItem();
    // convert line items response to line items post.
    let existingData = convertLineItemsToLineItemData(((_a = this.getOrder()) === null || _a === void 0 ? void 0 : _a.line_items) || []);
    if (lineItem && !(data === null || data === void 0 ? void 0 : data.ad_hoc_amount)) {
      lineItem.quantity = lineItem.quantity + 1;
    }
    return (await createOrUpdateOrder({
      id: (_b = this.getOrder()) === null || _b === void 0 ? void 0 : _b.id,
      data: {
        live_mode: this.mode === 'live',
        line_items: [
          ...(existingData || []),
          {
            ...lineItem,
            ...data,
          },
        ],
      },
      query: {
        ...query,
        form_id: this.formId,
      },
    }));
  }
  componentWillLoad() {
    Universe.create(this, this.state());
  }
  state() {
    return {
      busy: this.busy,
      error: this.error,
      order: this.getOrder(),
    };
  }
  render() {
    return (h("sc-form", { ref: el => (this.form = el), onScSubmit: () => {
        console.log('submit');
        this.addToCart();
      } }, this.error && (h("sc-alert", { open: !!this.error, type: "danger" }, h("span", { slot: "title" }, __('Error', 'surecart')), this.error)), h(Universe.Provider, { state: this.state() }, h("slot", null))));
  }
};
ScCartForm.style = "sc-cart-form { display: inline-block }";

export { ScCartForm as sc_cart_form };
