'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-cd6fab62.js');
const defaultI18n = require('./default-i18n-072e75d7.js');
require('./index-20b57ec7.js');
const fetch = require('./fetch-a8709225.js');
const lazy = require('./lazy-bc8baeab.js');
const price = require('./price-4a45d4fd.js');
const util = require('./util-125eb667.js');
const addQueryArgs = require('./add-query-args-17c551b6.js');
require('./_commonjsHelpers-537d719a.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 = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.quantityUpdatesEnabled = true;
  }
  componentWillLoad() {
    lazy.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) || defaultI18n.__('Something went wrong', 'surecart');
    }
    finally {
      this.loading = false;
    }
  }
  async getPrice() {
    if (!this.priceId)
      return;
    this.price = (await fetch.apiFetch({
      path: addQueryArgs.addQueryArgs(`surecart/v1/prices/${this.priceId}`, {
        expand: ['product'],
      }),
    }));
  }
  async getInvoice() {
    if (!this.subscriptionId)
      return;
    this.invoice = (await fetch.apiFetch({
      path: addQueryArgs.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) || defaultI18n.__('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) || defaultI18n.__('Something went wrong', 'surecart');
    }
    finally {
      this.busy = false;
    }
  }
  async onSubmit() {
    try {
      this.error = '';
      this.busy = true;
      await fetch.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) || defaultI18n.__('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 defaultI18n.__('Plan', 'surecart');
  }
  renderRenewalText() {
    var _a;
    if (this.isFutureInvoice()) {
      return (index.h("div", null, defaultI18n.__("You'll be switched to this plan", 'surecart'), ' ', index.h("strong", null, defaultI18n.__('at the end of your billing cycle on', 'surecart'), ' ', index.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 (index.h("div", null, defaultI18n.__("You'll be switched to this plan", 'surecart'), " ", index.h("strong", null, defaultI18n.__('immediately', 'surecart'))));
  }
  renderEmpty() {
    return index.h("slot", { name: "empty" }, defaultI18n.__('Something went wrong.', 'surecart'));
  }
  renderLoading() {
    return (index.h("div", null, index.h("sc-skeleton", { style: { width: '30%', marginBottom: '0.75em' } }), index.h("sc-skeleton", { style: { width: '20%', marginBottom: '0.75em' } }), index.h("sc-skeleton", { style: { width: '40%' } })));
  }
  renderContent() {
    var _a, _b;
    if (this.loading) {
      return this.renderLoading();
    }
    if (!this.invoice) {
      return this.renderEmpty();
    }
    return (index.h("div", { class: "new-plan" }, index.h("div", { class: "new-plan__heading" }, this.renderName(this.price)), index.h("div", null, index.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 }), ' ', price.intervalString(this.price)), index.h("div", { style: { fontSize: 'var(--sc-font-size-small)' } }, this.renderRenewalText())));
  }
  renderPrice(key) {
    var _a;
    return index.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 (index.h(index.Fragment, null, (_a = this.invoice.invoice_items) === null || _a === void 0 ? void 0 :
      _a.data.map(item => {
        var _a, _b, _c, _d, _e;
        return (index.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: price.intervalString(item === null || item === void 0 ? void 0 : item.price), onScUpdateQuantity: e => this.updateQuantity(e) }));
      }), index.h("sc-line-item", null, index.h("span", { slot: "description" }, defaultI18n.__('Subtotal', 'surecart')), index.h("span", { slot: "price" }, this.renderPrice('subtotal_amount'))), index.h("sc-coupon-form", { label: defaultI18n.__('Add Coupon Code'), onScApplyCoupon: e => this.applyCoupon(e), error: this.couponError }, defaultI18n.__('Add Coupon Code')), !!this.invoice.tax_amount && (index.h("sc-line-item", null, index.h("span", { slot: "description" }, ((_b = this.invoice) === null || _b === void 0 ? void 0 : _b.tax_label) || defaultI18n.__('Tax', 'surecart')), index.h("span", { slot: "price" }, this.renderPrice('tax_amount')))), this.invoice.total_amount !== this.invoice.amount_due && (index.h(index.Fragment, null, index.h("sc-divider", { style: { '--spacing': '0' } }), index.h("sc-line-item", null, index.h("span", { slot: "title" }, defaultI18n.__('Total', 'surecart')), index.h("span", { slot: "price" }, this.renderPrice('total_amount'))), !!this.invoice.proration_amount && (index.h("sc-line-item", null, index.h("span", { slot: "description" }, defaultI18n.__('Proration Credit', 'surecart')), index.h("span", { slot: "price" }, this.renderPrice('proration_amount')))))), index.h("sc-divider", { style: { '--spacing': '0' } }), index.h("sc-line-item", null, index.h("span", { slot: "description" }, defaultI18n.__('Payment', 'surecart')), index.h("a", { href: addQueryArgs.addQueryArgs(window.location.href, {
        action: 'payment',
      }), slot: "price-description" }, index.h("sc-flex", { "justify-content": "flex-start", "align-items": "center", style: { '--spacing': '0.5em' } }, util.capitalize(card === null || card === void 0 ? void 0 : card.brand), index.h("span", { style: { fontSize: '7px', whiteSpace: 'nowrap' } }, '\u2B24', " ", '\u2B24', " ", '\u2B24', " ", '\u2B24'), index.h("span", null, card === null || card === void 0 ? void 0 : card.last4), index.h("sc-icon", { name: "edit-3" })))), index.h("sc-line-item", { style: { '--price-size': 'var(--sc-font-size-x-large)' } }, index.h("span", { slot: "title" }, defaultI18n.__('Total Due Today', 'surecart')), this.isFutureInvoice() ? (index.h("sc-format-number", { type: "currency", currency: (_c = this.invoice) === null || _c === void 0 ? void 0 : _c.currency, slot: "price" })) : (index.h("span", { slot: "price" }, this.renderPrice('amount_due'))), index.h("span", { slot: "currency" }, this.invoice.currency))));
  }
  render() {
    return (index.h("div", { class: "upcoming-invoice" }, this.error && (index.h("sc-alert", { open: !!this.error, type: "danger" }, index.h("span", { slot: "title" }, defaultI18n.__('Error', 'surecart')), this.error)), index.h(index.Fragment, null, index.h("sc-dashboard-module", { heading: defaultI18n.__('New Plan', 'surecart'), class: "plan-preview", error: this.error }, index.h("sc-card", null, this.renderContent())), index.h("sc-dashboard-module", { heading: defaultI18n.__('Summary', 'surecart'), class: "plan-summary" }, index.h("sc-form", { onScFormSubmit: () => this.onSubmit() }, index.h("sc-card", null, this.renderSummary()), index.h("sc-button", { type: "primary", full: true, submit: true, loading: this.loading || this.busy, disabled: this.loading || this.busy }, defaultI18n.__('Confirm', 'surecart')))), index.h("sc-text", { style: { '--text-align': 'center', '--font-size': 'var(--sc-font-size-small)', '--line-height': 'var(--sc-line-height-normal)' } }, index.h("slot", { name: "terms" }))), this.busy && index.h("sc-block-ui", null)));
  }
  get el() { return index.getElement(this); }
};
ScUpcomingInvoice.style = scUpcomingInvoiceCss;

exports.sc_upcoming_invoice = ScUpcomingInvoice;
