import { r as registerInstance, c as createEvent, h, F as Fragment, g as getElement } from './index-f1d2a96f.js';
import { a as apiFetch } from './fetch-c0c608db.js';
import { g as getProcessorData } from './processor-6e16ca02.js';
import { p as pure } from './pure-4f52cebf.js';
import { s as stopAnimations, g as getAnimation, a as animateTo, c as shimKeyframesHeightAuto, b as setDefaultAnimation } from './animation-registry-e97b1b9d.js';
import './index-0a61debd.js';
import './_commonjsHelpers-9943807e.js';
import './add-query-args-f4c5962b.js';

const shouldReloadElement = (intent, order) => {
  var _a, _b;
  if (((_b = (_a = order === null || order === void 0 ? void 0 : order.line_items) === null || _a === void 0 ? void 0 : _a.pagination) === null || _b === void 0 ? void 0 : _b.count) === 0)
    return false; // we need items in the cart.
  if ((intent === null || intent === void 0 ? void 0 : intent.amount) === 0 && (order === null || order === void 0 ? void 0 : order.amount_due) !== 0)
    return true;
  if ((intent === null || intent === void 0 ? void 0 : intent.amount) > 0 && (order === null || order === void 0 ? void 0 : order.amount_due) === 0)
    return true;
  return false;
};

const scOrderStripePaymentElementCss = ":host{display:block}.loader{display:grid;height:128px;gap:2em}.loader__row{display:flex;align-items:flex-start;justify-content:space-between;gap:1em}.loader__details{display:grid;gap:0.5em}";

const ScOrderStripePaymentElement = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.scPaid = createEvent(this, "scPaid", 7);
    this.scPayError = createEvent(this, "scPayError", 7);
    this.scSetPaymentIntent = createEvent(this, "scSetPaymentIntent", 7);
    /** Available processors */
    this.processors = [];
    /** Payment mode. */
    this.mode = 'live';
    /** The currency code for the payment element. */
    this.currencyCode = 'usd';
  }
  async componentDidLoad() {
    var _a, _b, _c;
    this.paymentIntent = (await apiFetch({
      method: 'POST',
      path: 'surecart/v1/payment_intents',
      data: {
        amount: typeof ((_a = this === null || this === void 0 ? void 0 : this.order) === null || _a === void 0 ? void 0 : _a.amount_due) === 'number' ? this.order.amount_due : 100,
        currency: this.currencyCode,
        processor_type: 'stripe',
        live_mode: this.mode === 'live',
      },
    }));
    this.clientSecret = (_c = (_b = this.paymentIntent.processor_data) === null || _b === void 0 ? void 0 : _b.stripe) === null || _c === void 0 ? void 0 : _c.client_secret;
  }
  async updatePaymentIntent() {
    var _a, _b, _c;
    if (!((_a = this.paymentIntent) === null || _a === void 0 ? void 0 : _a.id)) {
      return;
    }
    this.paymentIntent = (await apiFetch({
      method: 'PATCH',
      path: `surecart/v1/payment_intents/${this.paymentIntent.id}`,
      data: {
        amount: this.order.amount_due,
        currency: this.currencyCode,
        processor_type: 'stripe',
        live_mode: this.mode === 'live',
      },
    }));
    this.clientSecret = (_c = (_b = this.paymentIntent.processor_data) === null || _b === void 0 ? void 0 : _b.stripe) === null || _c === void 0 ? void 0 : _c.client_secret;
  }
  async handleOrderChange() {
    if (!shouldReloadElement(this.paymentIntent, this.order))
      return;
    this.clientSecret = null;
    await this.updatePaymentIntent();
  }
  /**
   * When the payment intent is first set,
   * we need to sync it if we have an order.
   */
  async handlePaymentIntentChange() {
    // check if we should reload the payment intent
    if (shouldReloadElement(this.paymentIntent, this.order)) {
      await this.updatePaymentIntent();
    }
    // update payment intent in form when it's set.
    this.scSetPaymentIntent.emit({ processor: 'stripe', payment_intent: this.paymentIntent });
  }
  render() {
    // get account id and publishable key from the stripe processor for this mode.
    const data = getProcessorData(this.processors, 'stripe', this.mode);
    return (h("sc-stripe-payment-element", { order: this.order, address: this.address, "client-secret": this.clientSecret, publishableKey: data === null || data === void 0 ? void 0 : data.publishable_key, accountId: data === null || data === void 0 ? void 0 : data.account_id, key: this.clientSecret }));
  }
  static get watchers() { return {
    "order": ["handleOrderChange"],
    "paymentIntent": ["handlePaymentIntentChange"]
  }; }
};
ScOrderStripePaymentElement.style = scOrderStripePaymentElementCss;

const scSecureNoticeCss = ":host{display:block;--sc-secure-notice-icon-color:var(--sc-color-gray-300);--sc-secure-notice-font-size:var(--sc-font-size-small);--sc-secure-notice-color:var(--sc-color-gray-500)}.notice{color:var(--sc-secure-notice-color);font-size:var(--sc-secure-notice-font-size);display:flex;align-items:center}.notice__text{flex:1;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap}.notice__icon{color:var(--sc-secure-notice-icon-color);margin-right:5px}";

const ScSecureNotice = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
  }
  render() {
    return (h("div", { class: "notice", part: "base" }, h("svg", { class: "notice__icon", part: "icon", xmlns: "http://www.w3.org/2000/svg", width: "16", height: "16", viewBox: "0 0 512 512", fill: "currentColor" }, h("path", { d: "M368,192H352V112a96,96,0,1,0-192,0v80H144a64.07,64.07,0,0,0-64,64V432a64.07,64.07,0,0,0,64,64H368a64.07,64.07,0,0,0,64-64V256A64.07,64.07,0,0,0,368,192Zm-48,0H192V112a64,64,0,1,1,128,0Z" })), h("span", { class: "notice__text", part: "text" }, h("slot", { name: "prefix" }), h("slot", null), h("slot", { name: "suffix" }))));
  }
};
ScSecureNotice.style = scSecureNoticeCss;

const scStripeElementCss = "sc-stripe-element{display:block}sc-stripe-element sc-input{--sc-input-height-medium:auto}.sc-stripe *{font-family:var(--sc-input-font-family);font-weight:var(--sc-input-font-weight);font-size:var(--sc-input-font-size)}.sc-stripe fieldset{margin:0 15px 20px;padding:0;border-style:none;background-color:#7795f8;box-shadow:0 6px 9px rgba(50, 50, 93, 0.06), 0 2px 5px rgba(0, 0, 0, 0.08), inset 0 1px 0 #829fff;border-radius:4px}.sc-stripe .row{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;margin-left:15px}.sc-stripe .row+.row{border-top:1px solid #819efc}.sc-stripe label{width:15%;min-width:70px;padding:11px 0;color:#c4f0ff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sc-stripe input,.sc-stripe button{-webkit-appearance:none;-moz-appearance:none;appearance:none;outline:none;border-style:none}.sc-stripe input:-webkit-autofill{-webkit-text-fill-color:#fce883;transition:background-color 100000000s;-webkit-animation:1ms void-animation-out}.sc-stripe .StripeElement--webkit-autofill{background:transparent !important}.sc-stripe .StripeElement{width:100%;padding:var(--sc-input-spacing-small)}.sc-stripe input{width:100%;padding:11px;color:#fff;background-color:transparent;-webkit-animation:1ms void-animation-out}.sc-stripe input::-webkit-input-placeholder{color:#87bbfd}.sc-stripe input::-moz-placeholder{color:#87bbfd}.sc-stripe input:-ms-input-placeholder{color:#87bbfd}.sc-stripe button{display:block;width:calc(100% - 30px);height:40px;margin:40px 15px 0;background-color:#f6a4eb;box-shadow:0 6px 9px rgba(50, 50, 93, 0.06), 0 2px 5px rgba(0, 0, 0, 0.08), inset 0 1px 0 #ffb9f6;border-radius:4px;color:#fff;font-weight:600;cursor:pointer}.sc-stripe button:active{background-color:#d782d9;box-shadow:0 6px 9px rgba(50, 50, 93, 0.06), 0 2px 5px rgba(0, 0, 0, 0.08), inset 0 1px 0 #e298d8}.sc-stripe .error svg .base{fill:#fff}.sc-stripe .error svg .glyph{fill:#6772e5}.sc-stripe .error .message{color:#fff}.sc-stripe .success .icon .border{stroke:#87bbfd}.sc-stripe .success .icon .checkmark{stroke:#fff}.sc-stripe .success .title{color:#fff}.sc-stripe .success .message{color:#9cdbff}.sc-stripe .success .reset path{fill:#fff}";

const ScStripeElement = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.scPaid = createEvent(this, "scPaid", 7);
    this.scPayError = createEvent(this, "scPayError", 7);
    /** 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 pure.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))));
  }
  get el() { return getElement(this); }
  static get watchers() { return {
    "order": ["confirmPayment"]
  }; }
};
ScStripeElement.style = scStripeElementCss;

const scToggleCss = ":host{display:block;font-family:var(--sc-font-sans);--sc-toggle-padding:var(--sc-spacing-medium)}.details{border-radius:var(--sc-border-radius-medium);background-color:var(--sc-color-white);overflow-anchor:none}.details__radio{flex:0 0 auto;position:relative;display:inline-flex;align-items:center;justify-content:center;margin-right:0.75em;background-color:var(--sc-input-background-color);color:transparent;border-radius:50%;border:solid var(--sc-input-border-width) var(--sc-input-border-color);background-color:var(--sc-input-background-color);display:inline-flex;color:transparent;width:var(--sc-radio-size);height:var(--sc-radio-size);transition:var(--sc-transition-fast) border-color, var(--sc-transition-fast) background-color, var(--sc-transition-fast) color, var(--sc-transition-fast) box-shadow}.details__radio svg{width:100%;height:100%}.details--open .details__radio{color:var(--sc-color-white);border-color:var(--sc-color-primary-500);background-color:var(--sc-color-primary-500)}.details:not(.details--borderless){border:solid 1px var(--sc-color-gray-200)}.details--disabled{opacity:0.5}.details__header{display:flex;align-items:center;border-radius:inherit;padding:var(--sc-toggle-padding);user-select:none;cursor:pointer}.details__header:focus{outline:none}.details__header:focus-visible{box-shadow:var(--sc-focus-ring)}.details--disabled .details__header{cursor:not-allowed}.details--disabled .details__header:focus-visible{outline:none;box-shadow:none}.details__summary{flex:1 1 auto;display:flex;align-items:center}.details__summary-icon{flex:0 0 auto;display:flex;align-items:center;transition:var(--sc-transition-medium) transform ease}.details--open .details__summary-icon{transform:rotate(90deg)}.details__body{overflow:hidden;border-top:solid var(--sc-input-border-width) var(--sc-input-border-color)}.details--shady .details__body{background:var(--sc-color-gray-50)}.details__content{padding:var(--sc-toggle-padding)}";

const ScToggle = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.scShow = createEvent(this, "scShow", 7);
    this.scHide = createEvent(this, "scHide", 7);
    /** Indicates whether or not the details is open. You can use this in lieu of the show/hide methods. */
    this.open = false;
    /** Disables the details so it can't be toggled. */
    this.disabled = false;
    /** Is this a borderless toggle? */
    this.borderless = false;
    /** Is this a shady */
    this.shady = false;
    /** Should we show a radio control?  */
    this.showControl = false;
    /** Should we show the arrow icon? */
    this.showIcon = true;
    /** Are these collapsible? */
    this.collapsible = true;
  }
  componentDidLoad() {
    this.body.hidden = !this.open;
    this.body.style.height = this.open ? 'auto' : '0';
  }
  /** Shows the details. */
  async show() {
    if (this.open || this.disabled) {
      return undefined;
    }
    this.open = true;
  }
  /** Hides the details */
  async hide() {
    if (!this.open || this.disabled || !this.collapsible) {
      return undefined;
    }
    this.open = false;
  }
  handleSummaryClick() {
    if (!this.disabled) {
      if (this.open) {
        this.hide();
      }
      else {
        this.show();
      }
      this.header.focus();
    }
  }
  handleSummaryKeyDown(event) {
    if (event.key === 'Enter' || event.key === ' ') {
      event.preventDefault();
      if (this.open) {
        this.hide();
      }
      else {
        this.show();
      }
    }
    if (event.key === 'ArrowUp' || event.key === 'ArrowLeft') {
      event.preventDefault();
      this.hide();
    }
    if (event.key === 'ArrowDown' || event.key === 'ArrowRight') {
      event.preventDefault();
      this.show();
    }
  }
  async handleOpenChange() {
    if (this.open) {
      this.scShow.emit();
      await stopAnimations(this.body);
      this.body.hidden = false;
      const { keyframes, options } = getAnimation(this.el, 'details.show');
      await animateTo(this.body, shimKeyframesHeightAuto(keyframes, this.body.scrollHeight), options);
      this.body.style.height = 'auto';
    }
    else {
      this.scHide.emit();
      await stopAnimations(this.body);
      const { keyframes, options } = getAnimation(this.el, 'details.hide');
      await animateTo(this.body, shimKeyframesHeightAuto(keyframes, this.body.scrollHeight), options);
      this.body.hidden = true;
      this.body.style.height = 'auto';
    }
  }
  render() {
    return (h("div", { part: "base", class: {
        'details': true,
        'details--open': this.open,
        'details--disabled': this.disabled,
        'details--borderless': this.borderless,
        'details--shady': this.shady,
      } }, h("header", { ref: el => (this.header = el), part: "header", id: "header", class: "details__header", role: "button", "aria-expanded": this.open ? 'true' : 'false', "aria-controls": "content", "aria-disabled": this.disabled ? 'true' : 'false', tabindex: this.disabled ? '-1' : '0', onClick: () => this.handleSummaryClick(), onKeyDown: e => this.handleSummaryKeyDown(e) }, this.showControl && (h("span", { part: "radio", class: "details__radio" }, h("svg", { viewBox: "0 0 16 16" }, h("g", { stroke: "none", "stroke-width": "1", fill: "none", "fill-rule": "evenodd" }, h("g", { fill: "currentColor" }, h("circle", { cx: "8", cy: "8", r: "3.42857143" })))))), h("div", { part: "summary", class: "details__summary" }, h("slot", { name: "summary" }, this.summary)), this.showIcon && (h("span", { part: "summary-icon", class: "details__summary-icon" }, h("slot", { name: "icon" }, h("sc-icon", { name: "chevron-right" }))))), h("div", { class: "details__body", ref: el => (this.body = el) }, h("div", { part: "content", id: "content", class: "details__content", role: "region", "aria-labelledby": "header" }, h("slot", null)))));
  }
  get el() { return getElement(this); }
  static get watchers() { return {
    "open": ["handleOpenChange"]
  }; }
};
setDefaultAnimation('details.show', {
  keyframes: [
    { height: '0', opacity: '0' },
    { height: 'auto', opacity: '1' },
  ],
  options: { duration: 250, easing: 'ease' },
});
setDefaultAnimation('details.hide', {
  keyframes: [
    { height: 'auto', opacity: '1' },
    { height: '0', opacity: '0' },
  ],
  options: { duration: 250, easing: 'ease' },
});
ScToggle.style = scToggleCss;

const scTogglesCss = ":host{display:block;--toggle-spacing:0}::slotted(*){margin-bottom:var(--toggle-spacing)}::slotted([borderless]:not(:last-child)){border-bottom:1px solid var(--sc-color-gray-200)}";

const ScToggles = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    /** Should this function as an accordion? */
    this.accordion = false;
    /** Are these collapsible? */
    this.collapsible = true;
    /** Theme for the toggles */
    this.theme = 'default';
  }
  getToggles() {
    var _a, _b, _c;
    let slotted = this.el.shadowRoot.querySelector('slot');
    if (!slotted)
      return;
    return ((_c = (_b = (_a = slotted === null || slotted === void 0 ? void 0 : slotted.assignedNodes) === null || _a === void 0 ? void 0 : _a.call(slotted)) === null || _b === void 0 ? void 0 : _b.filter) === null || _c === void 0 ? void 0 : _c.call(_b, node => node.nodeName === 'SC-TOGGLE')) || [];
  }
  handleShowChange(event) {
    if (this.accordion) {
      this.getToggles().map(details => (details.open = event.target === details));
    }
  }
  handleCollapibleChange() {
    this.getToggles().map(details => (details.collapsible = this.collapsible));
  }
  componentDidLoad() {
    this.handleCollapibleChange();
    const toggles = this.getToggles();
    if ((toggles === null || toggles === void 0 ? void 0 : toggles.length) && !toggles.some(toggle => toggle.open)) {
      toggles[0].open = true;
    }
  }
  render() {
    const Tag = 'container' === this.theme ? 'sc-card' : 'div';
    return (h(Tag, { class: { toggles: true, [`toggles--theme-${this.theme}`]: true }, part: "base", "no-padding": true }, h("slot", null)));
  }
  get el() { return getElement(this); }
  static get watchers() { return {
    "collapsible": ["handleCollapibleChange"]
  }; }
};
ScToggles.style = scTogglesCss;

export { ScOrderStripePaymentElement as sc_order_stripe_payment_element, ScSecureNotice as sc_secure_notice, ScStripeElement as sc_stripe_element, ScToggle as sc_toggle, ScToggles as sc_toggles };
