import { Component, Element, Event, Fragment, h, Method, Prop, State, Watch } from '@stencil/core';
import { loadStripe } from '@stripe/stripe-js/pure';
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() {
    if (!this.publishableKey || !this.accountId) {
      return;
    }
    this.stripe = await loadStripe(this.publishableKey, { stripeAccount: this.accountId });
    this.elements = this.stripe.elements();
  }
  async confirmPayment(val) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
    // needs to be enabled
    if (this.disabled)
      return;
    // must be finalized
    if ((val === null || val === void 0 ? void 0 : val.status) !== 'finalized')
      return;
    // must be a stripe session
    if (((_a = val === null || val === void 0 ? void 0 : val.payment_intent) === null || _a === void 0 ? void 0 : _a.processor_type) !== 'stripe')
      return;
    // must have an external intent id
    if (!((_b = val === null || val === void 0 ? void 0 : val.payment_intent) === null || _b === void 0 ? void 0 : _b.external_intent_id))
      return;
    // must have a secret
    if (!((_e = (_d = (_c = val === null || val === void 0 ? void 0 : val.payment_intent) === null || _c === void 0 ? void 0 : _c.processor_data) === null || _d === void 0 ? void 0 : _d.stripe) === null || _e === void 0 ? void 0 : _e.client_secret))
      return;
    // need an external_type
    if (!((_h = (_g = (_f = val === null || val === void 0 ? void 0 : val.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.type))
      return;
    // prevent possible double-charges
    if (this.confirming)
      return;
    this.confirming = true;
    try {
      let response;
      if (((_l = (_k = (_j = val === null || val === void 0 ? void 0 : val.payment_intent) === null || _j === void 0 ? void 0 : _j.processor_data) === null || _k === void 0 ? void 0 : _k.stripe) === null || _l === void 0 ? void 0 : _l.type) == 'setup') {
        response = await this.confirmCardSetup((_o = (_m = val === null || val === void 0 ? void 0 : val.payment_intent) === null || _m === void 0 ? void 0 : _m.processor_data) === null || _o === void 0 ? void 0 : _o.stripe.client_secret);
      }
      else {
        response = await this.confirmCardPayment((_r = (_q = (_p = val === null || val === void 0 ? void 0 : val.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.client_secret);
      }
      if (response === null || response === void 0 ? void 0 : response.error) {
        this.error = response.error.message;
        throw response.error;
      }
      // paid
      this.scPaid.emit();
    }
    catch (e) {
      this.scPayError.emit(e);
      if (e.message) {
        this.error = e.message;
      }
    }
    finally {
      this.confirming = false;
    }
  }
  /** 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;
    }
    this.elements
      .create('card', {
      style: {
        base: {
          'color': '#303238',
          'fontSize': '16px',
          'fontSmoothing': 'antialiased',
          '::placeholder': {
            color: '#CFD7DF',
          },
        },
        invalid: {
          'color': '#e5424d',
          ':focus': {
            color: '#303238',
          },
        },
      },
    })
      .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-input", { class: "sc-stripe", size: this.size, label: this.label, hasFocus: this.hasFocus },
        h("div", { 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": "Order",
        "resolved": "Order",
        "references": {
          "Order": {
            "location": "import",
            "path": "../../../types"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "The checkout session object for finalizing intents"
      }
    },
    "accountId": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Your stripe connected account id."
      },
      "attribute": "account-id",
      "reflect": false
    },
    "publishableKey": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Stripe publishable key"
      },
      "attribute": "publishable-key",
      "reflect": false
    },
    "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
    }
  }; }
  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": {}
      }
    }]; }
  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": "order",
      "methodName": "confirmPayment"
    }]; }
}
