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

export { ScPaymentMethodsList as sc_payment_methods_list };
