import { r as registerInstance, c as createEvent, h, g as getElement } from './index-fd4790f6.js';
import { a as state } from './watchers-0c79cf4e.js';
import './watchers-5d458aa9.js';
import { s as state$1 } from './getters-a2fa2242.js';
import { s as state$3 } from './store-3645d641.js';
import { s as state$2 } from './store-d402e7c4.js';
import { _ as __ } from './default-i18n-2e663329.js';
import './index-53ddb833.js';
import { U as Universe } from './universe-e944e399.js';
import './index-26bbcef3.js';
import './add-query-args-f4c5962b.js';
import './watchers-e86a5dda.js';
import './util-c1d762c0.js';
import './index-6db066f7.js';

const scCheckoutCss = "sc-checkout{display:block;font-family:var(--sc-font-sans);font-size:var(--sc-checkout-font-size, 16px);position:relative}sc-checkout h3{font-size:var(--sc-input-label-font-size-medium)}sc-alert{margin-bottom:var(--sc-form-row-spacing)}.sc-checkout-container.sc-align-center{max-width:500px;margin-left:auto;margin-right:auto}.sc-checkout-container.sc-align-wide{max-width:800px;margin-left:auto;margin-right:auto}::slotted(*){font-family:var(--sc-font-sans)}";

const ScCheckout = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.scOrderUpdated = createEvent(this, "scOrderUpdated", 7);
    this.scOrderFinalized = createEvent(this, "scOrderFinalized", 7);
    this.scOrderError = createEvent(this, "scOrderError", 7);
    /** 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) {
    state.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());
    state$1.processors = this.processors;
    state$1.manualPaymentMethods = this.manualPaymentMethods;
    state$1.config.stripe.paymentElement = this.stripePaymentElement;
    state.formId = this.formId;
    state.mode = this.mode;
    state.product = this.product || null;
    state.currencyCode = this.currencyCode;
    state.groupId = this.el.id;
    state.abandonedCheckoutReturnUrl = this.abandonedCheckoutReturnUrl;
    state$2.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 = state.checkout) === null || _a === void 0 ? void 0 : _a.processor_data,
      state: this.checkoutState,
      formState: state$3.formState.value,
      paymentIntents: this.paymentIntents,
      successUrl: this.successUrl,
      bumps: (_c = (_b = state.checkout) === null || _b === void 0 ? void 0 : _b.recommended_bumps) === null || _c === void 0 ? void 0 : _c.data,
      order: state.checkout,
      abandonedCheckoutEnabled: (_d = state.checkout) === null || _d === void 0 ? void 0 : _d.abandoned_checkout_enabled,
      checkout: state.checkout,
      shippingEnabled: (_e = state.checkout) === null || _e === void 0 ? void 0 : _e.shipping_enabled,
      lineItems: ((_g = (_f = state.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: state$3.formState.value === 'loading',
      busy: ['updating', 'finalizing', 'paying', 'confirming'].includes(state$3.formState.value),
      paying: ['finalizing', 'paying', 'confirming'].includes(state$3.formState.value),
      empty: !['loading', 'updating'].includes(state$3.formState.value) && !((_k = (_j = (_h = state.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 = state.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 = state.checkout) === null || _o === void 0 ? void 0 : _o.tax_status,
      taxEnabled: (_p = state.checkout) === null || _p === void 0 ? void 0 : _p.tax_enabled,
      customerShippingAddress: typeof ((_q = state.checkout) === null || _q === void 0 ? void 0 : _q.customer) !== 'string' ? (_s = (_r = state.checkout) === null || _r === void 0 ? void 0 : _r.customer) === null || _s === void 0 ? void 0 : _s.shipping_address : {},
      shippingAddress: (_t = state.checkout) === null || _t === void 0 ? void 0 : _t.shipping_address,
      taxStatus: (_u = state.checkout) === null || _u === void 0 ? void 0 : _u.tax_status,
      taxIdentifier: (_v = state.checkout) === null || _v === void 0 ? void 0 : _v.tax_identifier,
      totalAmount: (_w = state.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 = state.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: state.checkout }, h("sc-form-state-provider", { onScSetCheckoutFormState: e => (this.checkoutState = e.detail) }, h("sc-form-error-provider", { checkoutState: state$3.formState.value, onScUpdateError: e => (this.error = e.detail) }, h("sc-form-components-validator", { order: state.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 }), state$3.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'))), state$3.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'))), state$3.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'))), state$3.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'))))));
  }
  get el() { return getElement(this); }
};
ScCheckout.style = scCheckoutCss;

export { ScCheckout as sc_checkout };
