import { proxyCustomElement, HTMLElement, h, Fragment } from '@stencil/core/internal/client';
import { _ as __ } from './default-i18n.js';
import './index2.js';
import { a as apiFetch } from './fetch.js';
import { o as onFirstVisible } from './lazy.js';
import { i as intervalString } from './price.js';
import { c as capitalize } from './util.js';
import { d as defineCustomElement$n } from './sc-alert2.js';
import { d as defineCustomElement$m } from './sc-block-ui2.js';
import { d as defineCustomElement$l } from './sc-button2.js';
import { d as defineCustomElement$k } from './sc-card2.js';
import { d as defineCustomElement$j } from './sc-coupon-form2.js';
import { d as defineCustomElement$i } from './sc-dashboard-module2.js';
import { d as defineCustomElement$h } from './sc-divider2.js';
import { d as defineCustomElement$g } from './sc-flex2.js';
import { d as defineCustomElement$f } from './sc-form2.js';
import { d as defineCustomElement$e } from './sc-form-control2.js';
import { d as defineCustomElement$d } from './sc-format-date2.js';
import { d as defineCustomElement$c } from './sc-format-number2.js';
import { d as defineCustomElement$b } from './sc-icon2.js';
import { d as defineCustomElement$a } from './sc-input2.js';
import { d as defineCustomElement$9 } from './sc-line-item2.js';
import { d as defineCustomElement$8 } from './sc-product-line-item2.js';
import { d as defineCustomElement$7 } from './sc-quantity-select2.js';
import { d as defineCustomElement$6 } from './sc-skeleton2.js';
import { d as defineCustomElement$5 } from './sc-spinner2.js';
import { d as defineCustomElement$4 } from './sc-tag2.js';
import { d as defineCustomElement$3 } from './sc-text2.js';
import { d as defineCustomElement$2 } from './sc-tooltip2.js';
import { a as addQueryArgs } from './add-query-args.js';

const scUpcomingInvoiceCss = ":host{display:block;position:relative}.upcoming-invoice{display:grid;gap:var(--sc-spacing-large)}.upcoming-invoice>*{display:grid;gap:var(--sc-spacing-medium)}.new-plan{display:grid;gap:0.25em;color:var(--sc-color-gray-600)}.new-plan__heading{font-weight:var(--sc-font-weight-bold);color:var(--sc-color-gray-800)}";

const ScUpcomingInvoice$1 = /*@__PURE__*/ proxyCustomElement(class extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.__attachShadow();
    this.quantityUpdatesEnabled = true;
  }
  componentWillLoad() {
    onFirstVisible(this.el, () => {
      this.fetchItems();
    });
  }
  isFutureInvoice() {
    return this.invoice.period_start_at >= new Date().getTime() / 1000;
  }
  async fetchItems() {
    var _a, _b;
    try {
      this.loading = true;
      await Promise.all([this.getInvoice(), this.getPrice()]);
    }
    catch (e) {
      console.error(e);
      this.error = ((_b = (_a = e === null || e === void 0 ? void 0 : e.additional_errors) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.message) || (e === null || e === void 0 ? void 0 : e.message) || __('Something went wrong', 'surecart');
    }
    finally {
      this.loading = false;
    }
  }
  async getPrice() {
    if (!this.priceId)
      return;
    this.price = (await apiFetch({
      path: addQueryArgs(`surecart/v1/prices/${this.priceId}`, {
        expand: ['product'],
      }),
    }));
  }
  async getInvoice() {
    if (!this.subscriptionId)
      return;
    this.invoice = (await apiFetch({
      path: addQueryArgs(`surecart/v1/subscriptions/${this.subscriptionId}/upcoming_invoice/`, {
        expand: [
          'invoice.subscription',
          'subscription.price',
          'subscription.payment_method',
          'payment_method.card',
          'invoice.discount',
          'invoice.invoice_items',
          'invoice_item.price',
          'price.product',
        ],
        subscription: {
          price: this.priceId,
          quantity: this.quantity,
          ...(this.adHocAmount ? { ad_hoc_amount: this.adHocAmount } : {}),
          ...(this.discount ? { discount: this.discount } : {}),
        },
      }),
    }));
    return this.invoice;
  }
  async applyCoupon(e) {
    try {
      this.couponError = '';
      this.busy = true;
      this.discount = {
        promotion_code: e.detail,
      };
      await this.getInvoice();
    }
    catch (e) {
      this.couponError = (e === null || e === void 0 ? void 0 : e.message) || __('Something went wrong', 'surecart');
    }
    finally {
      this.busy = false;
    }
  }
  async updateQuantity(e) {
    try {
      this.error = '';
      this.busy = true;
      this.quantity = e.detail;
      await this.getInvoice();
    }
    catch (e) {
      this.error = (e === null || e === void 0 ? void 0 : e.message) || __('Something went wrong', 'surecart');
    }
    finally {
      this.busy = false;
    }
  }
  async onSubmit() {
    try {
      this.error = '';
      this.busy = true;
      await apiFetch({
        path: `surecart/v1/subscriptions/${this.subscriptionId}`,
        method: 'PATCH',
        data: {
          price: this.priceId,
          quantity: this.quantity,
          ...(this.adHocAmount ? { ad_hoc_amount: this.adHocAmount } : {}),
          ...(this.discount ? { discount: this.discount } : {}),
        },
      });
      if (this.successUrl) {
        window.location.assign(this.successUrl);
      }
      else {
        this.busy = false;
      }
    }
    catch (e) {
      this.error = (e === null || e === void 0 ? void 0 : e.message) || __('Something went wrong', 'surecart');
      this.busy = false;
    }
  }
  renderName(price) {
    var _a;
    if (typeof (price === null || price === void 0 ? void 0 : price.product) !== 'string') {
      return (_a = price === null || price === void 0 ? void 0 : price.product) === null || _a === void 0 ? void 0 : _a.name;
    }
    return __('Plan', 'surecart');
  }
  renderRenewalText() {
    var _a;
    if (this.isFutureInvoice()) {
      return (h("div", null, __("You'll be switched to this plan", 'surecart'), ' ', h("strong", null, __('at the end of your billing cycle on', 'surecart'), ' ', h("sc-format-date", { type: "timestamp", date: (_a = this.invoice) === null || _a === void 0 ? void 0 : _a.period_start_at, month: "short", day: "numeric", year: "numeric" }))));
    }
    return (h("div", null, __("You'll be switched to this plan", 'surecart'), " ", h("strong", null, __('immediately', 'surecart'))));
  }
  renderEmpty() {
    return h("slot", { name: "empty" }, __('Something went wrong.', 'surecart'));
  }
  renderLoading() {
    return (h("div", null, h("sc-skeleton", { style: { width: '30%', marginBottom: '0.75em' } }), h("sc-skeleton", { style: { width: '20%', marginBottom: '0.75em' } }), h("sc-skeleton", { style: { width: '40%' } })));
  }
  renderContent() {
    var _a, _b;
    if (this.loading) {
      return this.renderLoading();
    }
    if (!this.invoice) {
      return this.renderEmpty();
    }
    return (h("div", { class: "new-plan" }, h("div", { class: "new-plan__heading" }, this.renderName(this.price)), h("div", null, h("sc-format-number", { type: "currency", currency: (_a = this === null || this === void 0 ? void 0 : this.invoice) === null || _a === void 0 ? void 0 : _a.currency, value: (_b = this === null || this === void 0 ? void 0 : this.invoice) === null || _b === void 0 ? void 0 : _b.total_amount }), ' ', intervalString(this.price)), h("div", { style: { fontSize: 'var(--sc-font-size-small)' } }, this.renderRenewalText())));
  }
  renderPrice(key) {
    var _a;
    return h("sc-format-number", { type: "currency", currency: this.invoice.currency, value: (_a = this.invoice) === null || _a === void 0 ? void 0 : _a[key] });
  }
  renderSummary() {
    var _a, _b, _c;
    if (this.loading) {
      return this.renderLoading();
    }
    if (!this.invoice) {
      return this.renderEmpty();
    }
    const { card } = this.invoice.subscription.payment_method;
    return (h(Fragment, null, (_a = this.invoice.invoice_items) === null || _a === void 0 ? void 0 :
      _a.data.map(item => {
        var _a, _b, _c, _d, _e;
        return (h("sc-product-line-item", { imageUrl: (_b = (_a = item.price) === null || _a === void 0 ? void 0 : _a.product) === null || _b === void 0 ? void 0 : _b.image_url, name: (_d = (_c = item.price) === null || _c === void 0 ? void 0 : _c.product) === null || _d === void 0 ? void 0 : _d.name, editable: this.quantityUpdatesEnabled, removable: false, quantity: item === null || item === void 0 ? void 0 : item.quantity, amount: item === null || item === void 0 ? void 0 : item.total_amount, currency: (_e = item === null || item === void 0 ? void 0 : item.price) === null || _e === void 0 ? void 0 : _e.currency, interval: intervalString(item === null || item === void 0 ? void 0 : item.price), onScUpdateQuantity: e => this.updateQuantity(e) }));
      }), h("sc-line-item", null, h("span", { slot: "description" }, __('Subtotal', 'surecart')), h("span", { slot: "price" }, this.renderPrice('subtotal_amount'))), h("sc-coupon-form", { label: __('Add Coupon Code'), onScApplyCoupon: e => this.applyCoupon(e), error: this.couponError }, __('Add Coupon Code')), !!this.invoice.tax_amount && (h("sc-line-item", null, h("span", { slot: "description" }, ((_b = this.invoice) === null || _b === void 0 ? void 0 : _b.tax_label) || __('Tax', 'surecart')), h("span", { slot: "price" }, this.renderPrice('tax_amount')))), this.invoice.total_amount !== this.invoice.amount_due && (h(Fragment, null, h("sc-divider", { style: { '--spacing': '0' } }), h("sc-line-item", null, h("span", { slot: "title" }, __('Total', 'surecart')), h("span", { slot: "price" }, this.renderPrice('total_amount'))), !!this.invoice.proration_amount && (h("sc-line-item", null, h("span", { slot: "description" }, __('Proration Credit', 'surecart')), h("span", { slot: "price" }, this.renderPrice('proration_amount')))))), h("sc-divider", { style: { '--spacing': '0' } }), h("sc-line-item", null, h("span", { slot: "description" }, __('Payment', 'surecart')), h("a", { href: addQueryArgs(window.location.href, {
        action: 'payment',
      }), slot: "price-description" }, h("sc-flex", { "justify-content": "flex-start", "align-items": "center", style: { '--spacing': '0.5em' } }, capitalize(card === null || card === void 0 ? void 0 : card.brand), h("span", { style: { fontSize: '7px', whiteSpace: 'nowrap' } }, '\u2B24', " ", '\u2B24', " ", '\u2B24', " ", '\u2B24'), h("span", null, card === null || card === void 0 ? void 0 : card.last4), h("sc-icon", { name: "edit-3" })))), h("sc-line-item", { style: { '--price-size': 'var(--sc-font-size-x-large)' } }, h("span", { slot: "title" }, __('Total Due Today', 'surecart')), this.isFutureInvoice() ? (h("sc-format-number", { type: "currency", currency: (_c = this.invoice) === null || _c === void 0 ? void 0 : _c.currency, slot: "price" })) : (h("span", { slot: "price" }, this.renderPrice('amount_due'))), h("span", { slot: "currency" }, this.invoice.currency))));
  }
  render() {
    return (h("div", { class: "upcoming-invoice" }, this.error && (h("sc-alert", { open: !!this.error, type: "danger" }, h("span", { slot: "title" }, __('Error', 'surecart')), this.error)), h(Fragment, null, h("sc-dashboard-module", { heading: __('New Plan', 'surecart'), class: "plan-preview", error: this.error }, h("sc-card", null, this.renderContent())), h("sc-dashboard-module", { heading: __('Summary', 'surecart'), class: "plan-summary" }, h("sc-form", { onScFormSubmit: () => this.onSubmit() }, h("sc-card", null, this.renderSummary()), h("sc-button", { type: "primary", full: true, submit: true, loading: this.loading || this.busy, disabled: this.loading || this.busy }, __('Confirm', 'surecart')))), h("sc-text", { style: { '--text-align': 'center', '--font-size': 'var(--sc-font-size-small)', '--line-height': 'var(--sc-line-height-normal)' } }, h("slot", { name: "terms" }))), this.busy && h("sc-block-ui", null)));
  }
  get el() { return this; }
  static get style() { return scUpcomingInvoiceCss; }
}, [1, "sc-upcoming-invoice", {
    "heading": [1],
    "successUrl": [1, "success-url"],
    "subscriptionId": [1, "subscription-id"],
    "priceId": [1, "price-id"],
    "quantity": [2],
    "discount": [1040],
    "payment_method": [1040],
    "quantityUpdatesEnabled": [4, "quantity-updates-enabled"],
    "adHocAmount": [2, "ad-hoc-amount"],
    "loading": [32],
    "busy": [32],
    "error": [32],
    "price": [32],
    "invoice": [32],
    "couponError": [32]
  }]);
function defineCustomElement$1() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["sc-upcoming-invoice", "sc-alert", "sc-block-ui", "sc-button", "sc-card", "sc-coupon-form", "sc-dashboard-module", "sc-divider", "sc-flex", "sc-form", "sc-form-control", "sc-format-date", "sc-format-number", "sc-icon", "sc-input", "sc-line-item", "sc-product-line-item", "sc-quantity-select", "sc-skeleton", "sc-spinner", "sc-tag", "sc-text", "sc-tooltip"];
  components.forEach(tagName => { switch (tagName) {
    case "sc-upcoming-invoice":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, ScUpcomingInvoice$1);
      }
      break;
    case "sc-alert":
      if (!customElements.get(tagName)) {
        defineCustomElement$n();
      }
      break;
    case "sc-block-ui":
      if (!customElements.get(tagName)) {
        defineCustomElement$m();
      }
      break;
    case "sc-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$l();
      }
      break;
    case "sc-card":
      if (!customElements.get(tagName)) {
        defineCustomElement$k();
      }
      break;
    case "sc-coupon-form":
      if (!customElements.get(tagName)) {
        defineCustomElement$j();
      }
      break;
    case "sc-dashboard-module":
      if (!customElements.get(tagName)) {
        defineCustomElement$i();
      }
      break;
    case "sc-divider":
      if (!customElements.get(tagName)) {
        defineCustomElement$h();
      }
      break;
    case "sc-flex":
      if (!customElements.get(tagName)) {
        defineCustomElement$g();
      }
      break;
    case "sc-form":
      if (!customElements.get(tagName)) {
        defineCustomElement$f();
      }
      break;
    case "sc-form-control":
      if (!customElements.get(tagName)) {
        defineCustomElement$e();
      }
      break;
    case "sc-format-date":
      if (!customElements.get(tagName)) {
        defineCustomElement$d();
      }
      break;
    case "sc-format-number":
      if (!customElements.get(tagName)) {
        defineCustomElement$c();
      }
      break;
    case "sc-icon":
      if (!customElements.get(tagName)) {
        defineCustomElement$b();
      }
      break;
    case "sc-input":
      if (!customElements.get(tagName)) {
        defineCustomElement$a();
      }
      break;
    case "sc-line-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$9();
      }
      break;
    case "sc-product-line-item":
      if (!customElements.get(tagName)) {
        defineCustomElement$8();
      }
      break;
    case "sc-quantity-select":
      if (!customElements.get(tagName)) {
        defineCustomElement$7();
      }
      break;
    case "sc-skeleton":
      if (!customElements.get(tagName)) {
        defineCustomElement$6();
      }
      break;
    case "sc-spinner":
      if (!customElements.get(tagName)) {
        defineCustomElement$5();
      }
      break;
    case "sc-tag":
      if (!customElements.get(tagName)) {
        defineCustomElement$4();
      }
      break;
    case "sc-text":
      if (!customElements.get(tagName)) {
        defineCustomElement$3();
      }
      break;
    case "sc-tooltip":
      if (!customElements.get(tagName)) {
        defineCustomElement$2();
      }
      break;
  } });
}
defineCustomElement$1();

const ScUpcomingInvoice = ScUpcomingInvoice$1;
const defineCustomElement = defineCustomElement$1;

export { ScUpcomingInvoice, defineCustomElement };
