import { Component, Fragment, h, Listen, Prop, State, Watch } from '@stencil/core';
import apiFetch from '../../../../functions/fetch';
import { addQueryArgs } from '@wordpress/url';
import { Universe } from 'stencil-wormhole';
import { baseUrl } from '../../../../services/session';
import { getOrder, setOrder } from '@store/checkouts';
import uiStore from '@store/ui';
export class ScCart {
  constructor() {
    /** 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',
            'recommended_bumps',
            'bump.price',
            '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))),
          this.uiState === 'busy' && h("sc-block-ui", { "z-index": 9 })))))));
  }
  static get is() { return "sc-cart"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() { return {
    "$": ["sc-cart.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["sc-cart.css"]
  }; }
  static get properties() { return {
    "formId": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "The form id to use for the cart."
      },
      "attribute": "form-id",
      "reflect": true
    },
    "header": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "The header for the popout."
      },
      "attribute": "header",
      "reflect": false
    },
    "checkoutLink": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "checkout-link",
      "reflect": false
    },
    "cartTemplate": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "The template for the cart to inject when opened."
      },
      "attribute": "cart-template",
      "reflect": false
    },
    "mode": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "'test' | 'live'",
        "resolved": "\"live\" | \"test\"",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Are we in test or live mode."
      },
      "attribute": "mode",
      "reflect": false,
      "defaultValue": "'live'"
    },
    "checkoutUrl": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "The checkout url for the button."
      },
      "attribute": "checkout-url",
      "reflect": false
    },
    "alwaysShow": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Should we force show the cart, even if there's a form on the page?"
      },
      "attribute": "always-show",
      "reflect": false
    }
  }; }
  static get states() { return {
    "open": {},
    "uiState": {},
    "error": {}
  }; }
  static get watchers() { return [{
      "propName": "open",
      "methodName": "handleOpenChange"
    }]; }
  static get listeners() { return [{
      "name": "scSetState",
      "method": "handleSetState",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "scError",
      "method": "handleErrorEvent",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "scCloseCart",
      "method": "handleCloseCart",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
