import { Component, Element, Event, Fragment, h, Method, Prop, State, Watch } from '@stencil/core';
import { loadStripe } from '@stripe/stripe-js/pure';
import { __ } from '@wordpress/i18n';
import { openWormhole } from 'stencil-wormhole';
import { state as selectedProcessor } from '@store/selected-processor';
import { availableProcessors } from '@store/processors/getters';
export class ScStripeElement {
  constructor() {
    /** Mode for the payment */
    this.mode = 'live';
    /** The input's size. */
    this.size = 'medium';
    /** The input's help text. Alternatively, you can use the help-text slot. */
    this.secureText = '';
    /** Should we show the label */
    this.showLabel = true;
  }
  async componentWillLoad() {
    const processor = (availableProcessors() || []).find(processor => processor.processor_type === 'stripe');
    if (!processor) {
      return;
    }
    const { account_id, publishable_key } = (processor === null || processor === void 0 ? void 0 : processor.processor_data) || {};
    try {
      this.stripe = await loadStripe(publishable_key, { stripeAccount: account_id });
      this.elements = this.stripe.elements();
    }
    catch (e) {
      this.error = (e === null || e === void 0 ? void 0 : e.message) || __('Stripe could not be loaded', 'surecart');
    }
  }
  /**
   * Watch order status and maybe confirm the order.
   */
  async maybeConfirmOrder(val) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y;
    // must be paying
    if (val !== 'paying')
      return;
    // this processor is not selected.
    if ((selectedProcessor === null || selectedProcessor === void 0 ? void 0 : selectedProcessor.id) !== 'stripe')
      return;
    // must be a stripe session
    if (((_b = (_a = this.order) === null || _a === void 0 ? void 0 : _a.payment_intent) === null || _b === void 0 ? void 0 : _b.processor_type) !== 'stripe')
      return;
    // must have an external intent id
    if (!((_d = (_c = this.order) === null || _c === void 0 ? void 0 : _c.payment_intent) === null || _d === void 0 ? void 0 : _d.external_intent_id))
      return;
    // must have a secret
    if (!((_h = (_g = (_f = (_e = this.order) === null || _e === void 0 ? void 0 : _e.payment_intent) === null || _f === void 0 ? void 0 : _f.processor_data) === null || _g === void 0 ? void 0 : _g.stripe) === null || _h === void 0 ? void 0 : _h.client_secret))
      return;
    // need an external_type
    if (!((_m = (_l = (_k = (_j = this.order) === null || _j === void 0 ? void 0 : _j.payment_intent) === null || _k === void 0 ? void 0 : _k.processor_data) === null || _l === void 0 ? void 0 : _l.stripe) === null || _m === void 0 ? void 0 : _m.type))
      return;
    // prevent possible double-charges
    if (this.confirming)
      return;
    this.confirming = true;
    try {
      let response;
      if (((_r = (_q = (_p = (_o = this.order) === null || _o === void 0 ? void 0 : _o.payment_intent) === null || _p === void 0 ? void 0 : _p.processor_data) === null || _q === void 0 ? void 0 : _q.stripe) === null || _r === void 0 ? void 0 : _r.type) == 'setup') {
        response = await this.confirmCardSetup((_u = (_t = (_s = this.order) === null || _s === void 0 ? void 0 : _s.payment_intent) === null || _t === void 0 ? void 0 : _t.processor_data) === null || _u === void 0 ? void 0 : _u.stripe.client_secret);
      }
      else {
        response = await this.confirmCardPayment((_y = (_x = (_w = (_v = this.order) === null || _v === void 0 ? void 0 : _v.payment_intent) === null || _w === void 0 ? void 0 : _w.processor_data) === null || _x === void 0 ? void 0 : _x.stripe) === null || _y === void 0 ? void 0 : _y.client_secret);
      }
      if (response === null || response === void 0 ? void 0 : response.error) {
        this.error = response.error.message;
        throw response.error;
      }
      this.scSetState.emit('PAID');
      // paid
      this.scPaid.emit();
    }
    catch (e) {
      this.scPayError.emit(e);
      if (e.message) {
        this.error = e.message;
      }
      this.confirming = false;
      this.scSetState.emit('REJECT');
    }
  }
  /** Confirm card payment */
  async confirmCardPayment(secret) {
    var _a, _b;
    return this.stripe.confirmCardPayment(secret, {
      payment_method: {
        card: this.element,
        billing_details: {
          ...(((_a = this === null || this === void 0 ? void 0 : this.order) === null || _a === void 0 ? void 0 : _a.name) ? { name: this.order.name } : {}),
          ...(((_b = this === null || this === void 0 ? void 0 : this.order) === null || _b === void 0 ? void 0 : _b.email) ? { email: this.order.email } : {}),
        },
      },
    });
  }
  /** Confirm card setup. */
  async confirmCardSetup(secret) {
    var _a, _b;
    return this.stripe.confirmCardSetup(secret, {
      payment_method: {
        card: this.element,
        billing_details: {
          ...(((_a = this === null || this === void 0 ? void 0 : this.order) === null || _a === void 0 ? void 0 : _a.name) ? { name: this.order.name } : {}),
          ...(((_b = this === null || this === void 0 ? void 0 : this.order) === null || _b === void 0 ? void 0 : _b.email) ? { email: this.order.email } : {}),
        },
      },
    });
  }
  componentDidLoad() {
    if (!this.elements) {
      return;
    }
    // get the computed styles.
    const styles = getComputedStyle(document.body);
    this.elements
      .create('card', {
      style: {
        base: {
          'color': styles.getPropertyValue('--sc-input-label-color'),
          'fontSize': '16px',
          'iconColor': styles.getPropertyValue('--sc-stripe-icon-color'),
          'fontSmoothing': 'antialiased',
          '::placeholder': {
            color: styles.getPropertyValue('--sc-input-placeholder-color'),
          },
        },
        invalid: {
          'color': styles.getPropertyValue('--sc-color-error-500'),
          ':focus': {
            color: styles.getPropertyValue('--sc-input-label-color'),
          },
        },
      },
    })
      .mount(this.container);
    this.element = this.elements.getElement('card');
    this.element.on('change', event => { var _a; return (this.error = ((_a = event === null || event === void 0 ? void 0 : event.error) === null || _a === void 0 ? void 0 : _a.message) ? event.error.message : ''); });
    this.element.on('focus', () => (this.hasFocus = true));
    this.element.on('blur', () => (this.hasFocus = false));
  }
  render() {
    return (h(Fragment, null,
      h("sc-form-control", { class: "sc-stripe", size: this.size, label: this.label },
        h("div", { class: "sc-stripe-element", ref: el => (this.container = el) })),
      this.error && (h("sc-text", { style: {
          'color': 'var(--sc-color-danger-500)',
          '--font-size': 'var(--sc-font-size-small)',
          'marginTop': '0.5em',
        } }, this.error))));
  }
  static get is() { return "sc-stripe-element"; }
  static get originalStyleUrls() { return {
    "$": ["sc-stripe-element.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["sc-stripe-element.css"]
  }; }
  static get properties() { return {
    "disabled": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Whether this field is disabled"
      },
      "attribute": "disabled",
      "reflect": false
    },
    "order": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Checkout",
        "resolved": "Checkout",
        "references": {
          "Checkout": {
            "location": "import",
            "path": "../../../types"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "The checkout session object for finalizing intents"
      }
    },
    "mode": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "'live' | 'test'",
        "resolved": "\"live\" | \"test\"",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Mode for the payment"
      },
      "attribute": "mode",
      "reflect": false,
      "defaultValue": "'live'"
    },
    "size": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "'small' | 'medium' | 'large'",
        "resolved": "\"large\" | \"medium\" | \"small\"",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "The input's size."
      },
      "attribute": "size",
      "reflect": true,
      "defaultValue": "'medium'"
    },
    "label": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "The input's label. Alternatively, you can use the label slot."
      },
      "attribute": "label",
      "reflect": false
    },
    "secureText": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "The input's help text. Alternatively, you can use the help-text slot."
      },
      "attribute": "secure-text",
      "reflect": false,
      "defaultValue": "''"
    },
    "showLabel": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Should we show the label"
      },
      "attribute": "show-label",
      "reflect": false,
      "defaultValue": "true"
    },
    "hasFocus": {
      "type": "boolean",
      "mutable": true,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Inputs focus"
      },
      "attribute": "has-focus",
      "reflect": true
    },
    "selectedProcessorId": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "ProcessorName",
        "resolved": "\"paypal\" | \"paypal-card\" | \"stripe\"",
        "references": {
          "ProcessorName": {
            "location": "import",
            "path": "../../../types"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "The selected processor id"
      },
      "attribute": "selected-processor-id",
      "reflect": false
    },
    "formState": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "FormState",
        "resolved": "\"confirmed\" | \"confirming\" | \"draft\" | \"expired\" | \"failure\" | \"finalizing\" | \"idle\" | \"loading\" | \"paid\" | \"paying\" | \"redirecting\" | \"updating\"",
        "references": {
          "FormState": {
            "location": "import",
            "path": "../../../types"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "The form state"
      },
      "attribute": "form-state",
      "reflect": false
    }
  }; }
  static get states() { return {
    "error": {},
    "confirming": {}
  }; }
  static get events() { return [{
      "method": "scPaid",
      "name": "scPaid",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "void",
        "resolved": "void",
        "references": {}
      }
    }, {
      "method": "scPayError",
      "name": "scPayError",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }, {
      "method": "scSetState",
      "name": "scSetState",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": "Set the state"
      },
      "complexType": {
        "original": "FormStateSetter",
        "resolved": "\"EXPIRE\" | \"FETCH\" | \"FINALIZE\" | \"PAID\" | \"PAYING\" | \"REJECT\" | \"RESOLVE\"",
        "references": {
          "FormStateSetter": {
            "location": "import",
            "path": "../../../types"
          }
        }
      }
    }]; }
  static get methods() { return {
    "confirmCardPayment": {
      "complexType": {
        "signature": "(secret: any) => Promise<any>",
        "parameters": [{
            "tags": [],
            "text": ""
          }],
        "references": {
          "Promise": {
            "location": "global"
          }
        },
        "return": "Promise<any>"
      },
      "docs": {
        "text": "Confirm card payment",
        "tags": []
      }
    },
    "confirmCardSetup": {
      "complexType": {
        "signature": "(secret: any) => Promise<any>",
        "parameters": [{
            "tags": [],
            "text": ""
          }],
        "references": {
          "Promise": {
            "location": "global"
          }
        },
        "return": "Promise<any>"
      },
      "docs": {
        "text": "Confirm card setup.",
        "tags": []
      }
    }
  }; }
  static get elementRef() { return "el"; }
  static get watchers() { return [{
      "propName": "formState",
      "methodName": "maybeConfirmOrder"
    }]; }
}
openWormhole(ScStripeElement, ['order', 'mode', 'selectedProcessorId', 'formState'], false);
