'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 addQueryArgs = require('./add-query-args-17c551b6.js');
require('./_commonjsHelpers-537d719a.js');

const scPaymentMethodsListCss = ":host{display:block;position:relative}.payment-methods-list{display:grid;gap:0.5em}.payment-methods-list sc-heading a{text-decoration:none;font-weight:var(--sc-font-weight-semibold);display:inline-flex;align-items:center;gap:0.25em;color:var(--sc-color-primary-500)}";

const ScPaymentMethodsList = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.paymentMethods = [];
  }
  /** Only fetch if visible */
  componentWillLoad() {
    lazy.onFirstVisible(this.el, () => {
      this.getPaymentMethods();
    });
    this.handleSlotChange();
  }
  handleSlotChange() {
    this.hasTitleSlot = !!this.el.querySelector('[slot="title"]');
  }
  async deleteMethod(method) {
    const r = confirm(defaultI18n.__('Are you sure you want to remove this payment method?', 'surecart'));
    if (!r)
      return;
    try {
      this.busy = true;
      (await fetch.apiFetch({
        path: `surecart/v1/payment_methods/${method === null || method === void 0 ? void 0 : method.id}/detach`,
        method: 'PATCH',
      }));
      // remove from view.
      this.paymentMethods = this.paymentMethods.filter(m => m.id !== method.id);
    }
    catch (e) {
      alert((e === null || e === void 0 ? void 0 : e.messsage) || defaultI18n.__('Something went wrong', 'surecart'));
    }
    finally {
      this.busy = false;
    }
  }
  async setDefault(method) {
    var _a;
    try {
      this.busy = true;
      (await fetch.apiFetch({
        path: `surecart/v1/customers/${(_a = method === null || method === void 0 ? void 0 : method.customer) === null || _a === void 0 ? void 0 : _a.id}`,
        method: 'PATCH',
        data: {
          default_payment_method: method.id,
        },
      }));
      this.paymentMethods = (await await fetch.apiFetch({
        path: addQueryArgs.addQueryArgs(`surecart/v1/payment_methods/`, {
          expand: ['card', 'customer', 'billing_agreement'],
          ...this.query,
        }),
      }));
    }
    catch (e) {
      alert((e === null || e === void 0 ? void 0 : e.messsage) || defaultI18n.__('Something went wrong', 'surecart'));
    }
    finally {
      this.busy = false;
    }
  }
  /** Get all paymentMethods */
  async getPaymentMethods() {
    try {
      this.loading = true;
      this.paymentMethods = (await await fetch.apiFetch({
        path: addQueryArgs.addQueryArgs(`surecart/v1/payment_methods/`, {
          expand: ['card', 'customer', 'billing_agreement'],
          ...this.query,
        }),
      }));
    }
    catch (e) {
      if (e === null || e === void 0 ? void 0 : e.message) {
        this.error = e.message;
      }
      else {
        this.error = defaultI18n.__('Something went wrong', 'surecart');
      }
      console.error(this.error);
    }
    finally {
      this.loading = false;
    }
  }
  renderLoading() {
    return (index.h("sc-card", { noPadding: true }, index.h("sc-stacked-list", null, index.h("sc-stacked-list-row", { style: { '--columns': '4' }, "mobile-size": 500 }, [...Array(4)].map(() => (index.h("sc-skeleton", { style: { width: '100px', display: 'inline-block' } })))))));
  }
  renderEmpty() {
    return (index.h("div", null, index.h("sc-divider", { style: { '--spacing': '0' } }), index.h("slot", { name: "empty" }, index.h("sc-empty", { icon: "credit-card" }, defaultI18n.__("You don't have any saved payment methods.", 'surecart')))));
  }
  renderList() {
    return this.paymentMethods.map(paymentMethod => {
      var _a, _b;
      const { id, card, customer, live_mode, billing_agreement } = paymentMethod;
      return (index.h("sc-stacked-list-row", { style: { '--columns': billing_agreement ? '2' : '3' } }, index.h("sc-flex", { "justify-content": "flex-start", "align-items": "center", style: { '--spacing': '0.5em' } }, index.h("div", { style: { width: '50px', lineHeight: '0' } }, !!(card === null || card === void 0 ? void 0 : card.brand) && index.h("sc-cc-logo", { style: { fontSize: '36px' }, brand: card === null || card === void 0 ? void 0 : card.brand }), billing_agreement && index.h("sc-icon", { style: { width: '50px' }, name: "paypal" })), !!(card === null || card === void 0 ? void 0 : card.last4) && (index.h("sc-flex", { "justify-content": "flex-start", "align-items": "center", style: { '--spacing': '0.5em' } }, 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))), !!((_a = billing_agreement) === null || _a === void 0 ? void 0 : _a.email) && (index.h("span", { style: { '--spacing': '0.5em', 'overflow': 'hidden', 'textOverflow': 'ellipsis', 'whiteSpace': 'nowrap' } }, (_b = billing_agreement) === null || _b === void 0 ? void 0 : _b.email))), !!(card === null || card === void 0 ? void 0 : card.exp_month) && (index.h("div", null, defaultI18n.__('Exp.', 'surecart'), " ", card === null || card === void 0 ? void 0 :
        card.exp_month, "/", card === null || card === void 0 ? void 0 :
        card.exp_year)), index.h("sc-flex", { "justify-content": "flex-start", "align-items": "center", style: { '--spacing': '0.5em', 'marginLeft': 'auto' } }, typeof customer !== 'string' && (customer === null || customer === void 0 ? void 0 : customer.default_payment_method) === id && index.h("sc-tag", { type: "info" }, defaultI18n.__('Default', 'surecart')), !live_mode && index.h("sc-tag", { type: "warning" }, defaultI18n.__('Test', 'surecart'))), index.h("sc-dropdown", { placement: "bottom-end", slot: "suffix" }, index.h("sc-icon", { name: "more-horizontal", slot: "trigger" }), index.h("sc-menu", null, typeof customer !== 'string' && (customer === null || customer === void 0 ? void 0 : customer.default_payment_method) !== id && (index.h("sc-menu-item", { onClick: () => this.setDefault(paymentMethod) }, defaultI18n.__('Make Default', 'surecart'))), index.h("sc-menu-item", { onClick: () => this.deleteMethod(paymentMethod) }, defaultI18n.__('Delete', 'surecart'))))));
    });
  }
  renderContent() {
    var _a;
    if (this.loading) {
      return this.renderLoading();
    }
    if (((_a = this.paymentMethods) === null || _a === void 0 ? void 0 : _a.length) === 0) {
      return this.renderEmpty();
    }
    return (index.h("sc-card", { "no-padding": true }, index.h("sc-stacked-list", null, this.renderList())));
  }
  render() {
    return (index.h("sc-dashboard-module", { class: "payment-methods-list", error: this.error }, index.h("span", { slot: "heading" }, index.h("slot", { name: "heading" }, this.heading || defaultI18n.__('Payment Methods', 'surecart'))), index.h("sc-flex", { slot: "end" }, index.h("sc-button", { type: "link", href: addQueryArgs.addQueryArgs(window.location.href, {
        action: 'index',
        model: 'charge',
      }) }, index.h("sc-icon", { name: "clock", slot: "prefix" }), defaultI18n.__('Payment History', 'surecart')), index.h("sc-button", { type: "link", href: addQueryArgs.addQueryArgs(window.location.href, {
        action: 'create',
        model: 'payment_method',
      }) }, index.h("sc-icon", { name: "plus", slot: "prefix" }), defaultI18n.__('Add', 'surecart'))), this.renderContent(), this.busy && index.h("sc-block-ui", { spinner: true })));
  }
  get el() { return index.getElement(this); }
};
ScPaymentMethodsList.style = scPaymentMethodsListCss;

exports.sc_payment_methods_list = ScPaymentMethodsList;
