'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-cd6fab62.js');
const defaultI18n = require('./default-i18n-072e75d7.js');
require('./index-20b57ec7.js');
const universe = require('./universe-df1c49ef.js');
const index$1 = require('./index-2fb0a3b9.js');
const index$2 = require('./index-c1a1f929.js');
const checkouts = require('./checkouts-ace88d0b.js');
const ui = require('./ui-c8c253d4.js');
require('./_commonjsHelpers-537d719a.js');
require('./fetch-a8709225.js');
require('./add-query-args-17c551b6.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) {
    index.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 checkouts.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
      checkouts.setOrder(order, this.formId);
      ui.uiStore.set('cart', { ...ui.uiStore.state.cart, ...{ open: true } });
    }
    catch (e) {
      console.error(e);
      this.error = (e === null || e === void 0 ? void 0 : e.message) || defaultI18n.__('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 = index$1.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 index$2.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.Universe.create(this, this.state());
  }
  state() {
    return {
      busy: this.busy,
      error: this.error,
      order: this.getOrder(),
    };
  }
  render() {
    return (index.h("sc-form", { ref: el => (this.form = el), onScSubmit: () => {
        console.log('submit');
        this.addToCart();
      } }, this.error && (index.h("sc-alert", { open: !!this.error, type: "danger" }, index.h("span", { slot: "title" }, defaultI18n.__('Error', 'surecart')), this.error)), index.h(universe.Universe.Provider, { state: this.state() }, index.h("slot", null))));
  }
};
ScCartForm.style = "sc-cart-form { display: inline-block }";

exports.sc_cart_form = ScCartForm;
