import { proxyCustomElement, HTMLElement, h, Fragment } from '@stencil/core/internal/client';
import { a as apiFetch } from './fetch.js';
import { U as Universe } from './universe.js';
import { b as baseUrl } from './index3.js';
import { g as getOrder, s as setOrder } from './checkouts.js';
import { u as uiStore } from './ui.js';
import { d as defineCustomElement$a } from './sc-alert2.js';
import { d as defineCustomElement$9 } from './sc-block-ui2.js';
import { d as defineCustomElement$8 } from './sc-cart-icon2.js';
import { d as defineCustomElement$7 } from './sc-cart-session-provider2.js';
import { d as defineCustomElement$6 } from './sc-drawer2.js';
import { d as defineCustomElement$5 } from './sc-error2.js';
import { d as defineCustomElement$4 } from './sc-icon2.js';
import { d as defineCustomElement$3 } from './sc-line-items-provider2.js';
import { d as defineCustomElement$2 } from './sc-spinner2.js';
import { a as addQueryArgs } from './add-query-args.js';

const scCartCss = ":host{--sc-drawer-header-spacing:var(--sc-spacing-large);--sc-drawer-body-spacing:var(--sc-spacing-large);--sc-drawer-footer-spacing:var(--sc-spacing-large)}.cart{font-size:16px}.cart__header{display:flex;align-items:center;justify-content:space-between;width:100%;font-size:1em}.cart__close{opacity:0.75;transition:opacity 0.25s ease;cursor:pointer}.cart__close:hover{opacity:1}::slotted(*){padding:var(--sc-drawer-header-spacing);background:var(--sc-panel-background-color);position:relative}::slotted(sc-line-items){flex:1 1 auto;overflow:auto;-webkit-overflow-scrolling:touch;min-height:200px}::slotted(:last-child){border-bottom:0 !important}sc-drawer::part(body){display:flex;flex-direction:column;box-sizing:border-box;padding:0;overflow:hidden}";

const ScCart$1 = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.__attachShadow();
    /** Is this open or closed? */
    this.open = null;
    /** Are we in test or live mode. */
    this.mode = 'live';
    /** The current UI state. */
    this.uiState = 'idle';
  }
  handleOpenChange() {
    uiStore.set('cart', { ...uiStore.state.cart, ...{ open: this.open } });
    if (this.open === true) {
      this.fetchOrder();
    }
  }
  order() {
    return getOrder(this.formId, this.mode);
  }
  setOrder(data) {
    setOrder(data, this.formId);
  }
  /**
   * Search for the sc-checkout component on a page to make sure
   * we don't show the cart on a checkout page.
   */
  pageHasForm() {
    return !!document.querySelector('sc-checkout');
  }
  /** Count the number of items in the cart. */
  getItemsCount() {
    var _a, _b;
    const items = (_b = (_a = this.order()) === null || _a === void 0 ? void 0 : _a.line_items) === null || _b === void 0 ? void 0 : _b.data;
    let count = 0;
    items.forEach(item => {
      count = count + (item === null || item === void 0 ? void 0 : item.quantity);
    });
    return count;
  }
  handleSetState(e) {
    this.uiState = e.detail;
  }
  /** Listen for error events in component. */
  handleErrorEvent(e) {
    this.error = e.detail;
    this.uiState = 'idle';
  }
  handleCloseCart() {
    this.open = false;
  }
  /** Fetch the order */
  async fetchOrder() {
    var _a;
    try {
      this.uiState = 'loading';
      const order = (await apiFetch({
        method: 'GET',
        path: addQueryArgs(`${baseUrl}${(_a = this.order()) === null || _a === void 0 ? void 0 : _a.id}`, {
          expand: [
            'line_items',
            'line_item.price',
            'price.product',
            'customer',
            'customer.shipping_address',
            'payment_intent',
            'discount',
            'discount.promotion',
            'discount.coupon',
            'shipping_address',
            'tax_identifier',
          ],
        }),
      }));
      this.setOrder(order);
    }
    catch (e) {
      console.error(e);
      throw e;
    }
    finally {
      this.uiState = 'idle';
    }
  }
  componentWillLoad() {
    Universe.create(this, this.state());
    this.open = !!uiStore.state.cart.open;
    uiStore.onChange('cart', cart => {
      this.open = cart.open;
    });
  }
  state() {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
    return {
      processor_data: (_a = this.order()) === null || _a === void 0 ? void 0 : _a.processor_data,
      uiState: this.uiState,
      checkoutLink: this.checkoutLink,
      loading: this.uiState === 'loading',
      busy: this.uiState === 'busy',
      navigating: this.uiState === 'navigating',
      empty: !((_d = (_c = (_b = this.order()) === null || _b === void 0 ? void 0 : _b.line_items) === null || _c === void 0 ? void 0 : _c.pagination) === null || _d === void 0 ? void 0 : _d.count),
      error: this.error,
      order: this.order(),
      lineItems: ((_f = (_e = this.order()) === null || _e === void 0 ? void 0 : _e.line_items) === null || _f === void 0 ? void 0 : _f.data) || [],
      tax_status: (_g = this.order()) === null || _g === void 0 ? void 0 : _g.tax_status,
      customerShippingAddress: typeof ((_h = this.order()) === null || _h === void 0 ? void 0 : _h.customer) !== 'string' ? (_k = (_j = this.order()) === null || _j === void 0 ? void 0 : _j.customer) === null || _k === void 0 ? void 0 : _k.shipping_address : {},
      shippingAddress: (_l = this.order()) === null || _l === void 0 ? void 0 : _l.shipping_address,
      taxStatus: (_m = this.order()) === null || _m === void 0 ? void 0 : _m.tax_status,
      formId: this.formId,
    };
  }
  render() {
    return (h(Fragment, null, this.order() && (h(Universe.Provider, { state: this.state() }, h("sc-cart-session-provider", { order: this.order(), "form-id": this.formId, "group-id": this.formId, onScUpdateOrderState: e => this.setOrder(e.detail), onScError: e => (this.error = e.detail) }, h("sc-cart-icon", { count: this.getItemsCount(), onClick: () => (this.open = !this.open) }), h("sc-drawer", { open: this.open, onScAfterHide: () => (this.open = false), onScAfterShow: () => (this.open = true) }, this.open === true && (h(Fragment, null, h("div", { class: "cart__header-suffix", slot: "header" }, h("slot", { name: "cart-header" }), h("sc-error", { style: { '--sc-alert-border-radius': '0' }, slot: "header", error: this.error, onScUpdateError: e => (this.error = e.detail) })), h("slot", null), h("div", { class: "cart_footer", slot: "footer" }, h("sc-cart-session-provider", { order: this.order(), "form-id": this.formId, "group-id": this.formId, onScUpdateOrderState: e => this.setOrder(e.detail), onScError: e => (this.error = e.detail) }, h("slot", { name: "cart-footer" }))))), this.uiState === 'busy' && h("sc-block-ui", { "z-index": 9 })))))));
  }
  static get watchers() { return {
    "open": ["handleOpenChange"]
  }; }
  static get style() { return scCartCss; }
}, [1, "sc-cart", {
    "formId": [513, "form-id"],
    "header": [1],
    "checkoutLink": [1, "checkout-link"],
    "cartTemplate": [1, "cart-template"],
    "mode": [1],
    "checkoutUrl": [1, "checkout-url"],
    "alwaysShow": [4, "always-show"],
    "open": [32],
    "uiState": [32],
    "error": [32]
  }, [[0, "scSetState", "handleSetState"], [0, "scError", "handleErrorEvent"], [0, "scCloseCart", "handleCloseCart"]]]);
function defineCustomElement$1() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["sc-cart", "sc-alert", "sc-block-ui", "sc-cart-icon", "sc-cart-session-provider", "sc-drawer", "sc-error", "sc-icon", "sc-line-items-provider", "sc-spinner"];
  components.forEach(tagName => { switch (tagName) {
    case "sc-cart":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, ScCart$1);
      }
      break;
    case "sc-alert":
      if (!customElements.get(tagName)) {
        defineCustomElement$a();
      }
      break;
    case "sc-block-ui":
      if (!customElements.get(tagName)) {
        defineCustomElement$9();
      }
      break;
    case "sc-cart-icon":
      if (!customElements.get(tagName)) {
        defineCustomElement$8();
      }
      break;
    case "sc-cart-session-provider":
      if (!customElements.get(tagName)) {
        defineCustomElement$7();
      }
      break;
    case "sc-drawer":
      if (!customElements.get(tagName)) {
        defineCustomElement$6();
      }
      break;
    case "sc-error":
      if (!customElements.get(tagName)) {
        defineCustomElement$5();
      }
      break;
    case "sc-icon":
      if (!customElements.get(tagName)) {
        defineCustomElement$4();
      }
      break;
    case "sc-line-items-provider":
      if (!customElements.get(tagName)) {
        defineCustomElement$3();
      }
      break;
    case "sc-spinner":
      if (!customElements.get(tagName)) {
        defineCustomElement$2();
      }
      break;
  } });
}
defineCustomElement$1();

const ScCart = ScCart$1;
const defineCustomElement = defineCustomElement$1;

export { ScCart, defineCustomElement };
