import { Component, Element, Event, h, Listen, Method, Prop, State } from '@stencil/core';
import { state as checkoutState } from '@store/checkout';
import { state as processorsState } from '@store/processors';
import { state as formState } from '@store/form';
import { state as userState } from '@store/user';
import { __ } from '@wordpress/i18n';
import { Universe } from 'stencil-wormhole';
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 = {};
  }
  handleOrderStateUpdate(e) {
    checkoutState.checkout = e.detail;
  }
  handleMethodChange(e) {
    this.method = 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() {
    const checkout = document.querySelector('sc-checkout');
    this.isDuplicate = !!checkout && checkout !== this.el;
    if (this.isDuplicate)
      return;
    Universe.create(this, this.state());
    processorsState.processors = this.processors;
    processorsState.manualPaymentMethods = this.manualPaymentMethods;
    processorsState.config.stripe.paymentElement = this.stripePaymentElement;
    checkoutState.formId = this.formId;
    checkoutState.mode = this.mode;
    checkoutState.product = this.product || null;
    checkoutState.currencyCode = this.currencyCode;
    checkoutState.groupId = this.el.id;
    checkoutState.abandonedCheckoutReturnUrl = this.abandonedCheckoutReturnUrl;
    userState.loggedIn = this.loggedIn;
  }
  state() {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
    return {
      processor: this.processor,
      method: this.method,
      selectedProcessorId: this.processor,
      manualPaymentMethods: this.manualPaymentMethods,
      processor_data: (_a = checkoutState.checkout) === null || _a === void 0 ? void 0 : _a.processor_data,
      state: this.checkoutState,
      formState: formState.formState.value,
      paymentIntents: this.paymentIntents,
      successUrl: this.successUrl,
      bumps: (_c = (_b = checkoutState.checkout) === null || _b === void 0 ? void 0 : _b.recommended_bumps) === null || _c === void 0 ? void 0 : _c.data,
      order: checkoutState.checkout,
      abandonedCheckoutEnabled: (_d = checkoutState.checkout) === null || _d === void 0 ? void 0 : _d.abandoned_checkout_enabled,
      checkout: checkoutState.checkout,
      shippingEnabled: (_e = checkoutState.checkout) === null || _e === void 0 ? void 0 : _e.shipping_enabled,
      lineItems: ((_g = (_f = checkoutState.checkout) === null || _f === void 0 ? void 0 : _f.line_items) === null || _g === void 0 ? void 0 : _g.data) || [],
      editLineItems: this.editLineItems,
      removeLineItems: this.removeLineItems,
      // checkout states
      loading: formState.formState.value === 'loading',
      busy: ['updating', 'finalizing', 'paying', 'confirming'].includes(formState.formState.value),
      paying: ['finalizing', 'paying', 'confirming'].includes(formState.formState.value),
      empty: !['loading', 'updating'].includes(formState.formState.value) && !((_k = (_j = (_h = checkoutState.checkout) === null || _h === void 0 ? void 0 : _h.line_items) === null || _j === void 0 ? void 0 : _j.pagination) === null || _k === void 0 ? void 0 : _k.count),
      // checkout states
      // stripe.
      stripePaymentElement: this.stripePaymentElement,
      stripePaymentIntent: (((_m = (_l = checkoutState.checkout) === null || _l === void 0 ? void 0 : _l.staged_payment_intents) === null || _m === void 0 ? void 0 : _m.data) || []).find(intent => intent.processor_type === 'stripe'),
      error: this.error,
      customer: this.customer,
      tax_status: (_o = checkoutState.checkout) === null || _o === void 0 ? void 0 : _o.tax_status,
      taxEnabled: (_p = checkoutState.checkout) === null || _p === void 0 ? void 0 : _p.tax_enabled,
      customerShippingAddress: typeof ((_q = checkoutState.checkout) === null || _q === void 0 ? void 0 : _q.customer) !== 'string' ? (_s = (_r = checkoutState.checkout) === null || _r === void 0 ? void 0 : _r.customer) === null || _s === void 0 ? void 0 : _s.shipping_address : {},
      shippingAddress: (_t = checkoutState.checkout) === null || _t === void 0 ? void 0 : _t.shipping_address,
      taxStatus: (_u = checkoutState.checkout) === null || _u === void 0 ? void 0 : _u.tax_status,
      taxIdentifier: (_v = checkoutState.checkout) === null || _v === void 0 ? void 0 : _v.tax_identifier,
      totalAmount: (_w = checkoutState.checkout) === null || _w === void 0 ? void 0 : _w.total_amount,
      taxProtocol: this.taxProtocol,
      lockedChoices: this.prices,
      products: this.productsEntities,
      prices: this.pricesEntities,
      country: 'US',
      loggedIn: this.loggedIn,
      emailExists: (_x = checkoutState.checkout) === null || _x === void 0 ? void 0 : _x.email_exists,
      formId: this.formId,
      mode: this.mode,
      currencyCode: this.currencyCode,
    };
  }
  render() {
    var _a, _b, _c, _d;
    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("sc-checkout-unsaved-changes-warning", { state: this.checkoutState }),
      h(Universe.Provider, { state: this.state() },
        h("sc-login-provider", { loggedIn: this.loggedIn, onScSetCustomer: e => (this.customer = e.detail), onScSetLoggedIn: e => (this.loggedIn = e.detail), order: checkoutState.checkout },
          h("sc-form-state-provider", { onScSetCheckoutFormState: e => (this.checkoutState = e.detail) },
            h("sc-form-error-provider", { checkoutState: formState.formState.value, onScUpdateError: e => (this.error = e.detail) },
              h("sc-form-components-validator", { order: checkoutState.checkout, disabled: this.disableComponentsValidation, taxProtocol: this.taxProtocol },
                h("sc-order-confirm-provider", { "success-url": this.successUrl, successText: this.successText },
                  h("sc-session-provider", { ref: el => (this.sessionProvider = el), prices: this.prices, persist: this.persistSession, onScError: e => (this.error = e.detail) },
                    h("slot", null))))))),
        this.state().busy && h("sc-block-ui", { class: "busy-block-ui", "z-index": 30 }),
        formState.formState.value === 'finalizing' && (h("sc-block-ui", { "z-index": 30, spinner: true, style: { '--sc-block-ui-opacity': '0.75' } }, ((_a = this.loadingText) === null || _a === void 0 ? void 0 : _a.finalizing) || __('Submitting order...', 'surecart'))),
        formState.formState.value === 'paying' && (h("sc-block-ui", { "z-index": 30, spinner: true, style: { '--sc-block-ui-opacity': '0.75' } }, ((_b = this.loadingText) === null || _b === void 0 ? void 0 : _b.paying) || __('Processing payment...', 'surecart'))),
        formState.formState.value === 'confirming' && (h("sc-block-ui", { "z-index": 30, spinner: true, style: { '--sc-block-ui-opacity': '0.75' } }, ((_c = this.loadingText) === null || _c === void 0 ? void 0 : _c.confirming) || __('Finalizing order...', 'surecart'))),
        formState.formState.value === 'redirecting' && (h("sc-block-ui", { "z-index": 30, spinner: true, style: { '--sc-block-ui-opacity': '0.75' } }, ((_d = this.loadingText) === null || _d === void 0 ? void 0 : _d.confirmed) || __('Success! Redirecting...', 'surecart'))))));
  }
  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": "[]"
    },
    "product": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Product",
        "resolved": "Product",
        "references": {
          "Product": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "A product to pre-fill the form."
      }
    },
    "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": true,
      "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."
      }
    },
    "manualPaymentMethods": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "ManualPaymentMethod[]",
        "resolved": "ManualPaymentMethod[]",
        "references": {
          "ManualPaymentMethod": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Manual payment methods 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"
    },
    "abandonedCheckoutReturnUrl": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "The abandoned checkout return url."
      },
      "attribute": "abandoned-checkout-return-url",
      "reflect": false
    },
    "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"
    },
    "loadingText": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "{\n    finalizing: string;\n    paying: string;\n    confirming: string;\n    confirmed: string;\n  }",
        "resolved": "{ finalizing: string; paying: string; confirming: string; confirmed: string; }",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Text for the loading states of the form."
      }
    },
    "successText": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "{\n    title: string;\n    description: string;\n    button: string;\n  }",
        "resolved": "{ title: string; description: string; button: string; }",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Success text for the form."
      }
    }
  }; }
  static get states() { return {
    "pricesEntities": {},
    "productsEntities": {},
    "checkoutState": {},
    "error": {},
    "processor": {},
    "method": {},
    "isManualProcessor": {},
    "paymentIntents": {},
    "isDuplicate": {}
  }; }
  static get events() { return [{
      "method": "scOrderUpdated",
      "name": "scOrderUpdated",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Checkout has been updated."
      },
      "complexType": {
        "original": "Checkout",
        "resolved": "Checkout",
        "references": {
          "Checkout": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      }
    }, {
      "method": "scOrderFinalized",
      "name": "scOrderFinalized",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Checkout has been finalized."
      },
      "complexType": {
        "original": "Checkout",
        "resolved": "Checkout",
        "references": {
          "Checkout": {
            "location": "import",
            "path": "../../../../types"
          }
        }
      }
    }, {
      "method": "scOrderError",
      "name": "scOrderError",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Checkout 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<Checkout | NodeJS.Timeout>",
        "parameters": [{
            "tags": [],
            "text": ""
          }],
        "references": {
          "Promise": {
            "location": "global"
          },
          "Checkout": {
            "location": "import",
            "path": "../../../../types"
          },
          "NodeJS": {
            "location": "global"
          }
        },
        "return": "Promise<Checkout | Timeout>"
      },
      "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": "scUpdateOrderState",
      "method": "handleOrderStateUpdate",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "scSetMethod",
      "method": "handleMethodChange",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "scAddEntities",
      "method": "handleAddEntities",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
