import { Component, Element, Event, h, Listen, Method, Prop, State } from '@stencil/core';
import { __ } from '@wordpress/i18n';
import { Universe } from 'stencil-wormhole';
import { getOrder } from '../../../../store/checkouts';
export class ScCheckout {
  constructor() {
    /** An array of prices to pre-fill in the form. */
    this.prices = [];
    /** Are we in test or live mode. */
    this.mode = 'live';
    /** Currency to use for this checkout. */
    this.currencyCode = 'usd';
    /** Whether to persist the session in the browser between visits. */
    this.persistSession = true;
    /** Where to go on success */
    this.successUrl = '';
    /** Can we edit line items? */
    this.editLineItems = true;
    /** Can we remove line items? */
    this.removeLineItems = true;
    /** Use the Stripe payment element. */
    this.stripePaymentElement = false;
    /** Stores fetched prices for use throughout component.  */
    this.pricesEntities = {};
    /** Stores fetched products for use throughout component.  */
    this.productsEntities = {};
    /** Loading states for different parts of the form. */
    this.checkoutState = 'idle';
    /** The currenly selected processor */
    this.processor = 'stripe';
    /** Holds the payment intents for the checkout. */
    this.paymentIntents = {};
  }
  handleSetPaymentIntent(e) {
    var _a, _b;
    const paymentIntent = (_a = e.detail) === null || _a === void 0 ? void 0 : _a.payment_intent;
    const processor = (_b = e.detail) === null || _b === void 0 ? void 0 : _b.processor;
    this.paymentIntents[processor] = paymentIntent;
  }
  handleProcessorChange(e) {
    this.processor = e.detail;
  }
  handleAddEntities(e) {
    const { products, prices } = e.detail;
    // add products.
    if (Object.keys((products === null || products === void 0 ? void 0 : products.length) || {})) {
      this.productsEntities = {
        ...this.productsEntities,
        ...products,
      };
    }
    // add prices.
    if (Object.keys((prices === null || prices === void 0 ? void 0 : prices.length) || {})) {
      this.pricesEntities = {
        ...this.pricesEntities,
        ...prices,
      };
    }
  }
  /**
   * Submit the form
   */
  async submit({ skip_validation } = { skip_validation: false }) {
    if (!skip_validation) {
      await this.validate();
    }
    return await this.sessionProvider.finalize();
  }
  /**
   * Validate the form.
   */
  async validate() {
    const form = this.el.querySelector('sc-form');
    return await form.validate();
  }
  componentWillLoad() {
    Universe.create(this, this.state());
    this.isDuplicate = document.querySelector('sc-checkout') !== this.el;
  }
  order() {
    return getOrder(this === null || this === void 0 ? void 0 : this.formId, this.mode);
  }
  state() {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
    return {
      processor: this.processor,
      processors: this.processors,
      processor_data: (_a = this.order()) === null || _a === void 0 ? void 0 : _a.processor_data,
      state: this.checkoutState,
      paymentIntents: this.paymentIntents,
      successUrl: this.successUrl,
      order: this.order(),
      shippingEnabled: (_b = this.order()) === null || _b === void 0 ? void 0 : _b.shipping_enabled,
      lineItems: ((_d = (_c = this.order()) === null || _c === void 0 ? void 0 : _c.line_items) === null || _d === void 0 ? void 0 : _d.data) || [],
      editLineItems: this.editLineItems,
      removeLineItems: this.removeLineItems,
      // checkout states
      loading: this.checkoutState === 'loading',
      busy: ['updating', 'finalizing', 'paid', 'confirmed'].includes(this.checkoutState),
      paying: ['finalizing', 'paid', 'confirmed'].includes(this.checkoutState),
      empty: !['loading', 'updating'].includes(this.checkoutState) && !((_g = (_f = (_e = this.order()) === null || _e === void 0 ? void 0 : _e.line_items) === null || _f === void 0 ? void 0 : _f.pagination) === null || _g === void 0 ? void 0 : _g.count),
      // checkout states
      // stripe.
      stripePaymentElement: this.stripePaymentElement,
      error: this.error,
      customer: this.customer,
      tax_status: (_h = this.order()) === null || _h === void 0 ? void 0 : _h.tax_status,
      customerShippingAddress: typeof ((_j = this.order()) === null || _j === void 0 ? void 0 : _j.customer) !== 'string' ? (_l = (_k = this.order()) === null || _k === void 0 ? void 0 : _k.customer) === null || _l === void 0 ? void 0 : _l.shipping_address : {},
      shippingAddress: (_m = this.order()) === null || _m === void 0 ? void 0 : _m.shipping_address,
      taxStatus: (_o = this.order()) === null || _o === void 0 ? void 0 : _o.tax_status,
      taxIdentifier: (_p = this.order()) === null || _p === void 0 ? void 0 : _p.tax_identifier,
      taxProtocol: this.taxProtocol,
      lockedChoices: this.prices,
      products: this.productsEntities,
      prices: this.pricesEntities,
      country: 'US',
      loggedIn: this.loggedIn,
      formId: this.formId,
      mode: this.mode,
      currencyCode: this.currencyCode,
    };
  }
  render() {
    if (this.isDuplicate) {
      return h("sc-alert", { open: true }, __('Due to processor restrictions, only one checkout form is allowed on the page.', 'surecart'));
    }
    return (h("div", { class: {
        'sc-checkout-container': true,
        'sc-align-center': this.alignment === 'center',
        'sc-align-wide': this.alignment === 'wide',
        'sc-align-full': this.alignment === 'full',
      } },
      h(Universe.Provider, { state: this.state() },
        h("sc-form-state-provider", { onScSetCheckoutFormState: e => (this.checkoutState = e.detail) },
          h("sc-form-error-provider", { order: this.order(), onScUpdateError: e => (this.error = e.detail) },
            h("sc-form-components-validator", { order: this.order(), disabled: this.disableComponentsValidation, taxProtocol: this.taxProtocol },
              h("sc-order-confirm-provider", { order: this.order(), "success-url": this.successUrl, "form-id": this.formId, mode: this.mode },
                h("sc-session-provider", { ref: el => (this.sessionProvider = el), prices: this.prices, stripePaymentElement: this.stripePaymentElement, paymentIntents: this.paymentIntents, persist: this.persistSession, modified: this.modified, mode: this.mode, "form-id": this.formId, "group-id": this.el.id, processor: this.processor, "currency-code": this.currencyCode, onScError: e => (this.error = e.detail) },
                  h("slot", null)))))),
        this.state().busy && h("sc-block-ui", { "z-index": 9 }))));
  }
  static get is() { return "sc-checkout"; }
  static get originalStyleUrls() { return {
    "$": ["sc-checkout.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["sc-checkout.css"]
  }; }
  static get properties() { return {
    "prices": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Array<PriceChoice>",
        "resolved": "PriceChoice[]",
        "references": {
          "Array": {
            "location": "global"
          },
          "PriceChoice": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "An array of prices to pre-fill in the form."
      },
      "defaultValue": "[]"
    },
    "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'"
    },
    "formId": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "The checkout form id"
      },
      "attribute": "form-id",
      "reflect": false
    },
    "modified": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "When the form was modified."
      },
      "attribute": "modified",
      "reflect": false
    },
    "currencyCode": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Currency to use for this checkout."
      },
      "attribute": "currency-code",
      "reflect": false,
      "defaultValue": "'usd'"
    },
    "persistSession": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Whether to persist the session in the browser between visits."
      },
      "attribute": "persist-session",
      "reflect": false,
      "defaultValue": "true"
    },
    "successUrl": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Where to go on success"
      },
      "attribute": "success-url",
      "reflect": false,
      "defaultValue": "''"
    },
    "customer": {
      "type": "unknown",
      "mutable": true,
      "complexType": {
        "original": "Customer",
        "resolved": "Customer",
        "references": {
          "Customer": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Stores the current customer"
      }
    },
    "alignment": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "'center' | 'wide' | 'full'",
        "resolved": "\"center\" | \"full\" | \"wide\"",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Alignment"
      },
      "attribute": "alignment",
      "reflect": false
    },
    "taxProtocol": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "TaxProtocol",
        "resolved": "TaxProtocol",
        "references": {
          "TaxProtocol": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "The account tax protocol"
      }
    },
    "loggedIn": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Is this user logged in?"
      },
      "attribute": "logged-in",
      "reflect": false
    },
    "disableComponentsValidation": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Should we disable components validation"
      },
      "attribute": "disable-components-validation",
      "reflect": false
    },
    "processors": {
      "type": "unknown",
      "mutable": true,
      "complexType": {
        "original": "Processor[]",
        "resolved": "Processor[]",
        "references": {
          "Processor": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Processors enabled for this form."
      }
    },
    "editLineItems": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Can we edit line items?"
      },
      "attribute": "edit-line-items",
      "reflect": false,
      "defaultValue": "true"
    },
    "removeLineItems": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Can we remove line items?"
      },
      "attribute": "remove-line-items",
      "reflect": false,
      "defaultValue": "true"
    },
    "stripePaymentElement": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Use the Stripe payment element."
      },
      "attribute": "stripe-payment-element",
      "reflect": false,
      "defaultValue": "false"
    }
  }; }
  static get states() { return {
    "pricesEntities": {},
    "productsEntities": {},
    "checkoutState": {},
    "error": {},
    "processor": {},
    "paymentIntents": {},
    "isDuplicate": {}
  }; }
  static get events() { return [{
      "method": "scOrderUpdated",
      "name": "scOrderUpdated",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Order has been updated."
      },
      "complexType": {
        "original": "Order",
        "resolved": "Order",
        "references": {
          "Order": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      }
    }, {
      "method": "scOrderFinalized",
      "name": "scOrderFinalized",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Order has been finalized."
      },
      "complexType": {
        "original": "Order",
        "resolved": "Order",
        "references": {
          "Order": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      }
    }, {
      "method": "scOrderError",
      "name": "scOrderError",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Order has an error."
      },
      "complexType": {
        "original": "ResponseError",
        "resolved": "ResponseError",
        "references": {
          "ResponseError": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      }
    }]; }
  static get methods() { return {
    "submit": {
      "complexType": {
        "signature": "({ skip_validation }?: { skip_validation: boolean; }) => Promise<any>",
        "parameters": [{
            "tags": [],
            "text": ""
          }],
        "references": {
          "Promise": {
            "location": "global"
          }
        },
        "return": "Promise<any>"
      },
      "docs": {
        "text": "Submit the form",
        "tags": []
      }
    },
    "validate": {
      "complexType": {
        "signature": "() => Promise<boolean>",
        "parameters": [],
        "references": {
          "Promise": {
            "location": "global"
          },
          "HTMLScFormElement": {
            "location": "global"
          }
        },
        "return": "Promise<boolean>"
      },
      "docs": {
        "text": "Validate the form.",
        "tags": []
      }
    }
  }; }
  static get elementRef() { return "el"; }
  static get listeners() { return [{
      "name": "scSetPaymentIntent",
      "method": "handleSetPaymentIntent",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "scSetProcessor",
      "method": "handleProcessorChange",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "scAddEntities",
      "method": "handleAddEntities",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
