import { proxyCustomElement, HTMLElement, createEvent, h } from '@stencil/core/internal/client';
import { a as apiFetch } from './fetch.js';
import { p as parseFormData } from './form-data.js';
import { e as expand } from './index3.js';
import { c as clearOrder } from './checkouts.js';
import { a as addQueryArgs } from './add-query-args.js';

const ScOrderConfirmProvider = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.__attachShadow();
    this.scConfirmed = createEvent(this, "scConfirmed", 7);
    this.scOrderPaid = createEvent(this, "scOrderPaid", 7);
    this.scError = createEvent(this, "scError", 7);
    /** Are we in test or live mode. */
    this.mode = 'live';
  }
  /** Listen for paid event. This is triggered by Stripe or Paypal elements when payment succeeds. */
  handlePaidEvent() {
    this.confirmOrder();
  }
  /** Confirm the order. */
  async confirmOrder() {
    var _a, _b;
    const json = await this.el.querySelector('sc-form').getFormJson();
    let data = parseFormData(json);
    try {
      const confirmed = (await apiFetch({
        method: 'PATCH',
        path: addQueryArgs(`surecart/v1/checkouts/${(_a = this.order) === null || _a === void 0 ? void 0 : _a.id}/confirm`, [expand]),
        data,
      }));
      // emit the confirmed event to trigger listeners to redirect to the success url, etc.
      this.scConfirmed.emit();
      // emit the order paid event for tracking scripts.
      this.scOrderPaid.emit(confirmed);
    }
    catch (e) {
      console.error(e);
      this.scError.emit(e);
    }
    finally {
      const order = (_b = this.order) === null || _b === void 0 ? void 0 : _b.id;
      // make sure we clear the order state no matter what.
      clearOrder(this.formId, this.mode);
      // we always want to redirect, regardless of the outcome here.
      window.location.assign(addQueryArgs(this.successUrl, { order }));
    }
  }
  render() {
    return h("slot", null);
  }
  get el() { return this; }
}, [1, "sc-order-confirm-provider", {
    "formId": [2, "form-id"],
    "mode": [1],
    "order": [16],
    "successUrl": [1, "success-url"]
  }, [[0, "scPaid", "handlePaidEvent"]]]);
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["sc-order-confirm-provider"];
  components.forEach(tagName => { switch (tagName) {
    case "sc-order-confirm-provider":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, ScOrderConfirmProvider);
      }
      break;
  } });
}
defineCustomElement();

export { ScOrderConfirmProvider as S, defineCustomElement as d };
