import { c as ne, p as k, f as H, r as te, b as O, d as ae, u as ie, m as tt, i as ee, k as Re, e as Se, t as me, h as ye, s as rt, g as Ce, a as xe, j as nt, n as De, o as Pe, q as at } from "./AssetItem-ufNA-vj9.js";
import { a as we, o as it } from "./index-client-DOkVNeOk.js";
import { t as se, z as U, w as j, x as F, A as Ie, y as re, r as oe, l as R, m as G, bG as Z, n as ce, D as T, v as q, o as _e, E as t, F as ve, C as X, p as le, bH as Ee, J, P as K, I as $, bu as be, W as Q, bI as st, bm as he, bo as Ne, bp as Be, L as pe, N as ue, O as fe, bJ as ot, bv as ge, bK as Oe, K as Me, by as ct, X as ze, bL as lt, bM as $e, bN as dt, bO as Te, bP as ke, bQ as ut, bR as ft, bS as vt } from "./index-DRgrWhNH.js";
import { a as pt } from "./App-C7TSmMh1.js";
import { B as yt } from "./ButtonBack-De1k3L47.js";
import { p as gt } from "./event-modifiers-D4czZCB6.js";
import { L as mt } from "./Loader-Cz9tCQ0T.js";
import { B as Le } from "./Button-Dvas4qfY.js";
import { w as je } from "./ProgressVideo.service-BmjtnZZl.js";
var wt = H('<div class="crtw-relative crtw-flex crtw-py-2 crtw-px-4 crtw-items-center"><div class="crtw-flex-grow crtw-border-t crtw-border-gray-400"></div> <span class="crtw-flex-shrink crtw-mx-4 crtw-text-gray-400"> </span> <div class="crtw-flex-grow crtw-border-t crtw-border-gray-400"></div></div>');
function Fe(u, e) {
  if (new.target) return ne({ component: Fe, ...u });
  se(e, !0);
  let a = k(e, "text", 7, "OR");
  var n = {
    get text() {
      return a();
    },
    set text(o = "OR") {
      a(o), R();
    },
    $set: ie,
    $on: (o, w) => ae(e, o, w)
  }, r = wt(), i = U(j(r), 2), l = j(i, !0);
  return F(i), Ie(2), F(r), re(() => te(l, a())), O(u, r), oe(n);
}
const _t = "data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='22'%20height='22'%20viewBox='0%200%2024%2024'%3e%3cpath%20fill='%23bbb'%20d='M17%209.761v-4.761c0-2.761-2.238-5-5-5-2.763%200-5%202.239-5%205v4.761c-1.827%201.466-3%203.714-3%206.239%200%204.418%203.582%208%208%208s8-3.582%208-8c0-2.525-1.173-4.773-3-6.239zm-8-4.761c0-1.654%201.346-3%203-3s3%201.346%203%203v3.587c-.927-.376-1.938-.587-3-.587s-2.073.211-3%20.587v-3.587zm4%2011.723v2.277h-2v-2.277c-.596-.347-1-.984-1-1.723%200-1.104.896-2%202-2s2%20.896%202%202c0%20.738-.404%201.376-1%201.723z'/%3e%3c/svg%3e";
var bt = H('<button type="submit"><!></button>');
const ht = {
  hash: "svelte-m3cnza",
  code: ".active.svelte-m3cnza {background-color:#ffff;font-weight:500;color:#000;}.btn-disabled.svelte-m3cnza {pointer-events:none;background-color:#d0d2d5;}"
};
function Ae(u, e) {
  if (new.target) return ne({ component: Ae, ...u });
  se(e, !1), tt(u, ht);
  let a = k(e, "onClick", 12), n = k(e, "text", 12), r = k(e, "disabled", 12, !1), i = k(e, "isLoading", 12, !1), l = k(e, "isActive", 12, !1);
  var o = {
    get onClick() {
      return a();
    },
    set onClick(f) {
      a(f), R();
    },
    get text() {
      return n();
    },
    set text(f) {
      n(f), R();
    },
    get disabled() {
      return r();
    },
    set disabled(f) {
      r(f), R();
    },
    get isLoading() {
      return i();
    },
    set isLoading(f) {
      i(f), R();
    },
    get isActive() {
      return l();
    },
    set isActive(f) {
      l(f), R();
    },
    $set: ie,
    $on: (f, h) => ae(e, f, h)
  }, w = bt();
  let x;
  var v = j(w);
  {
    var b = (f) => {
      mt(f, {});
    }, _ = (f) => {
      var h = me();
      re(() => te(h, n())), O(f, h);
    };
    ee(v, (f) => {
      i() ? f(b) : f(_, !1);
    });
  }
  return F(w), re(() => x = Re(w, 1, `crtw-flex crtw-justify-center crtw-items-center crtw-w-full crtw-h-[50px] crtw-cursor-pointer crtw-border crtw-border-gray-300
  crtw-rounded crtw-font-['poppins'] crtw-text-gray-600 svelte-m3cnza`, null, x, {
    "btn-disabled": r() || i(),
    active: l()
  })), Se("click", w, gt(function(...f) {
    a()?.apply(this, f);
  })), O(u, w), oe(o);
}
var Ct = H("<div> </div>"), xt = H("<!> <!>", 1), Pt = H('<div><div class="crtw-text-right crtw-text-[13px] crtw-text-gray-400 crtw-mb-6"><div class="crtw-break-words"> </div> <div> </div></div> <div class="crtw-font-bold crtw-text-xl"> </div> <div class="crtw-flex crtw-justify-between crtw-mb-3 crtw-text-gray-600 crtw-font-bold"><!></div> <div class="crtw-flex crtw-bg-gray-200 crtw-rounded-md crtw-p-px"><!> <!></div> <hr class="crtw-block crtw-border-t-2 crtw-border-gray-200 crtw-w-1/2 crtw-mx-auto crtw-mt-3.5 crtw-mb-[15px]"/> <!> <div class="crtw-flex crtw-w-full crtw-justify-center crtw-items-center"><img alt=""/><span class="crtw-text-sm crtw-text-gray-400 crtw-ml-1">Payments are secure and encrypted</span></div> <div class="crtw-mt-1.5"><!></div></div>');
function Ue(u, e) {
  if (new.target) return ne({ component: Ue, ...u });
  se(e, !1);
  const a = G();
  let n = k(e, "isLoading", 12), r = k(e, "options", 12), { user: i, title: l, subtitle: o, onBackClick: w, isCardDisabled: x } = r(), v = G(x ? Z.CREDENZA_BALANCE : Z.CREDIT_CARD);
  ce(() => q(r()), () => {
    T(a, r().isCredezaValueDisabled);
  }), _e();
  var b = {
    get isLoading() {
      return n();
    },
    set isLoading(P) {
      n(P), R();
    },
    get options() {
      return r();
    },
    set options(P) {
      r(P), R();
    },
    $set: ie,
    $on: (P, D) => ae(e, P, D)
  };
  ye();
  var _ = Pt();
  let f;
  var h = j(_), d = j(h), S = j(d, !0);
  F(d);
  var g = U(d, 2), N = j(g, !0);
  F(g), F(h);
  var m = U(h, 2), A = j(m, !0);
  F(m);
  var C = U(m, 2), M = j(C);
  {
    var W = (P) => {
      var D = Ct(), z = j(D, !0);
      F(D), re(() => te(z, o)), O(P, D);
    };
    ee(M, (P) => {
      o && P(W);
    });
  }
  F(C);
  var p = U(C, 2), s = j(p);
  {
    let P = ve(() => (t(v), q(Z), X(() => t(v) === Z.CREDIT_CARD)));
    Ae(s, {
      text: "Credit Card",
      onClick: () => T(v, Z.CREDIT_CARD),
      get isActive() {
        return t(P);
      },
      get disabled() {
        return x;
      }
    });
  }
  var c = U(s, 2);
  {
    let P = ve(() => (t(v), q(Z), X(() => t(v) === Z.CREDENZA_BALANCE)));
    Ae(c, {
      text: "Credenza Balance",
      onClick: () => T(v, Z.CREDENZA_BALANCE),
      get isActive() {
        return t(P);
      },
      get disabled() {
        return t(a);
      }
    });
  }
  F(p);
  var y = U(p, 4);
  {
    var I = (P) => {
      var D = xt(), z = le(D);
      Ce(z, e, "card-provider-switch", {});
      var de = U(z, 2);
      Ce(de, e, "credit-card", {}), O(P, D);
    }, E = (P) => {
      var D = xe(), z = le(D);
      Ce(z, e, "cred-balance", {}), O(P, D);
    };
    ee(y, (P) => {
      t(v), q(Z), X(() => t(v) === Z.CREDIT_CARD) ? P(I) : (t(v), q(Z), X(() => t(v) === Z.CREDENZA_BALANCE) && P(E, 1));
    });
  }
  var L = U(y, 2), B = j(L);
  Ie(), F(L);
  var Y = U(L, 2), V = j(Y);
  return yt(V, {
    get onClick() {
      return w;
    }
  }), F(Y), F(_), re(() => {
    f = Re(_, 1, "cpui-payment crtw-text-left crtw-w-full", null, f, { "crtw-hidden": n() }), te(S, X(() => i?.email || i?.pending?.email || "")), te(N, X(() => i?.phone || i?.pending?.phone || "")), te(A, l), rt(B, "src", _t);
  }), O(u, _), oe(b);
}
var Et = H('<span class="crtw-text-xs crtw-text-stone-200"> </span>'), At = H('<div class="crtw-text-base crtw-mb-1.5">Credit card details</div> <div id="cpui-card-element" class="crtw-border crtw-border-gray-300 crtw-rounded crtw-px-2.5 crtw-py-4 crtw-mb-2.5 crtw-w-full"></div> <div id="card-errors" role="alert"></div> <!> <!>', 1);
function Ge(u, e) {
  if (new.target) return ne({ component: Ge, ...u });
  se(e, !1);
  let a = k(e, "options", 12), n = k(e, "isPaymentDisabled", 12), r = k(e, "isLoading", 12), i = k(e, "totalToPay", 12);
  const l = 0.5, o = +i() < l;
  let { isCardFocused: w, onPay: x, currencySymbol: v = "$" } = a();
  var b = {
    get options() {
      return a();
    },
    set options(g) {
      a(g), R();
    },
    get isPaymentDisabled() {
      return n();
    },
    set isPaymentDisabled(g) {
      n(g), R();
    },
    get isLoading() {
      return r();
    },
    set isLoading(g) {
      r(g), R();
    },
    get totalToPay() {
      return i();
    },
    set totalToPay(g) {
      i(g), R();
    },
    $set: ie,
    $on: (g, N) => ae(e, g, N)
  };
  ye();
  var _ = At(), f = U(le(_), 2), h = U(f, 4);
  {
    let g = ve(() => o ? `Minimum card payment: ${v}${l}` : `Pay ${v}${i()}`), N = ve(() => n() || o);
    Le(h, {
      get text() {
        return t(g);
      },
      get onClick() {
        return x;
      },
      get disabled() {
        return t(N);
      },
      get isLoading() {
        return r();
      },
      set isLoading(m) {
        r(m);
      },
      $$legacy: !0
    });
  }
  var d = U(h, 2);
  {
    var S = (g) => {
      var N = Et(), m = j(N);
      F(N), re(() => te(m, `Fee of ${q(a()), X(() => a().feeToApply * 100) ?? ""}% is automatically added.`)), O(g, N);
    };
    ee(d, (g) => {
      q(a()), X(() => a().feeToApply) && g(S);
    });
  }
  return re(() => nt(f, w ? "border-color: #121e2b" : "")), O(u, _), oe(b);
}
var Lt = H('You do not have enough stored value to make this payment. <span class="crtw-text-black crtw-cursor-pointer" role="button" tabindex="0"> </span>', 1), Tt = H('<div class="crtw-w-full crtw-text-center crtw-my-5"><div class="crtw-text-3xl crtw-text-black crtw-font-bold"><!></div> <div class="crtw-mb-5 crtw-text-gray-600"><!></div> <!></div>');
function qe(u, e) {
  if (new.target) return ne({ component: qe, ...u });
  se(e, !1);
  const a = G(), n = G(), r = G(), i = G(), l = G();
  let o = k(e, "options", 12), { credAlias: w, onPay: x, onGetCred: v } = o();
  ce(() => q(o()), () => {
    T(a, o().isLoading);
  }), ce(() => q(o()), () => {
    T(n, o().isPaymentDisabled);
  }), ce(() => q(o()), () => {
    T(r, o().formattedBalance);
  }), ce(() => q(o()), () => {
    T(i, o().totalToPay);
  }), ce(() => q(o()), () => {
    T(l, o().balance);
  }), _e();
  var b = {
    get options() {
      return o();
    },
    set options(p) {
      o(p), R();
    },
    $set: ie,
    $on: (p, s) => ae(e, p, s)
  };
  ye();
  var _ = Tt(), f = j(_), h = j(f);
  {
    var d = (p) => {
      var s = me("INSUFFICIENT FUNDS");
      O(p, s);
    }, S = Ee(() => (t(i), t(l), X(() => Number(t(i)) > t(l)))), g = (p) => {
      var s = me();
      re(() => te(s, `${t(r) ?? ""} ${w ?? ""}`)), O(p, s);
    };
    ee(h, (p) => {
      t(S) ? p(d) : p(g, !1);
    });
  }
  F(f);
  var N = U(f, 2), m = j(N);
  {
    var A = (p) => {
      var s = Lt(), c = U(le(s)), y = j(c);
      F(c), re(() => te(y, `Click to get some ${w ?? ""}`)), Se("click", c, v), O(p, s);
    }, C = Ee(() => (t(i), t(l), X(() => Number(t(i)) > t(l)))), M = (p) => {
      var s = me("Your balance after purchase");
      O(p, s);
    };
    ee(m, (p) => {
      t(C) ? p(A) : p(M, !1);
    });
  }
  F(N);
  var W = U(N, 2);
  {
    let p = ve(() => `Pay ${t(i)} ${w}`);
    Le(W, {
      get text() {
        return t(p);
      },
      get onClick() {
        return x;
      },
      get disabled() {
        return t(n);
      },
      get isLoading() {
        return t(a);
      }
    });
  }
  return F(_), O(u, _), oe(b);
}
var kt = H('<div id="ctui-wallet-pay" class="crtw-w-full crtw-my-4" style="dispay: none;"><div id="ctui-payment-request-button"></div></div>');
function We(u, e) {
  if (new.target) return ne({ component: We, ...u });
  se(e, !1);
  var a = this && this.__awaiter || function(v, b, _, f) {
    function h(d) {
      return d instanceof _ ? d : new _(function(S) {
        S(d);
      });
    }
    return new (_ || (_ = Promise))(function(d, S) {
      function g(A) {
        try {
          m(f.next(A));
        } catch (C) {
          S(C);
        }
      }
      function N(A) {
        try {
          m(f.throw(A));
        } catch (C) {
          S(C);
        }
      }
      function m(A) {
        A.done ? d(A.value) : h(A.value).then(g, N);
      }
      m((f = f.apply(v, b || [])).next());
    });
  };
  let n = k(e, "doPayment", 12), r = k(e, "stripe", 12), i = k(e, "stripeElements", 12), l = k(e, "priceCents", 12), o = k(e, "isLoading", 12);
  we(() => a(void 0, void 0, void 0, function* () {
    const v = r().paymentRequest({
      country: "US",
      currency: "usd",
      total: { label: "Apple/Google payment", amount: l() / 100 },
      requestPayerName: !0,
      requestPayerEmail: !0
    });
    if (!(yield v.canMakePayment())) return;
    const _ = document.getElementById("ctui-wallet-pay");
    _ && (_.style.display = "crtw-block"), i().create("paymentRequestButton", {
      paymentRequest: v,
      style: { paymentRequestButton: { height: "48px" } }
    }).mount("#ctui-payment-request-button"), v.on("token", (h) => a(void 0, void 0, void 0, function* () {
      o(!0);
      try {
        yield n()(h.token.id), yield h.complete("success");
      } catch (d) {
        yield h.complete("error"), J(K.ERROR, { error: d });
      }
      o(!1);
    }));
  }));
  var w = {
    get doPayment() {
      return n();
    },
    set doPayment(v) {
      n(v), R();
    },
    get stripe() {
      return r();
    },
    set stripe(v) {
      r(v), R();
    },
    get stripeElements() {
      return i();
    },
    set stripeElements(v) {
      i(v), R();
    },
    get priceCents() {
      return l();
    },
    set priceCents(v) {
      l(v), R();
    },
    get isLoading() {
      return o();
    },
    set isLoading(v) {
      o(v), R();
    },
    $set: ie,
    $on: (v, b) => ae(e, v, b)
  };
  ye();
  var x = kt();
  return O(u, x), oe(w);
}
const Rt = {
  base: {
    color: "#121e2b",
    fontSize: "12px",
    "::placeholder": {
      color: "#d9d9d9"
    }
  },
  invalid: {
    color: "#fa755a"
  }
}, He = (u) => new Promise((e, a) => {
  const n = document.createElement("script");
  n.src = u, document.body.appendChild(n), n.addEventListener("load", () => e(n)), n.addEventListener("error", () => a(n));
}), St = async (u, e, a = 10) => {
  let n = 0;
  for (; n < a; ) {
    const r = await fetch(`${u}/orders/${e}`, {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${$(be)}`
      },
      method: "GET"
    });
    if (!r.ok) throw new Error("Failed to get order details");
    const i = await r.json();
    if (i.status !== "NEW")
      return i;
    n++, n < a && await new Promise((l) => setTimeout(l, 2e3));
  }
  throw new Error("Order attempts exceeded. Please try again later.");
}, Dt = async (u, e, a = 5) => {
  let n = 0;
  for (; n < a; ) {
    const r = await fetch(`${u}/orders/completed/${e}`, {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${$(be)}`
      },
      method: "GET"
    });
    if (r.status === 204) {
      if (n++, n < a)
        continue;
      throw new Error("No content received after multiple attempts");
    }
    if (!r.ok) throw new Error("Failed to get order details");
    const i = await r.json();
    if (i.status === "PAYMENT_ERROR")
      throw new Error(`Order failed: ${i.status}`);
    return i;
  }
}, It = (u, e) => {
  if (u.every((a) => a === null))
    throw new Error(`All transactions failed. 
${e}`);
}, Nt = (u) => {
  const e = u.filter((a) => a.error).map(
    (a) => `Name: ${a.metadata?.name || a.directive.resource_id}, reason: ${a.error}`
  ).join(`
`);
  if (u?.every((a) => a.status === "ERROR"))
    throw new Error("All transactions failed.}");
  return e;
}, Ye = async ({
  stripeChargeId: u,
  title: e,
  digest: a,
  subtitle: n,
  amount: r,
  currency: i
}) => {
  const { credenza: l, receiptTarget: o, clientId: w } = $(Q), x = o ? o.filter(
    (b) => {
      const _ = $(he);
      if (_)
        return _[b];
    }
  ) : [ot.EMAIL];
  let v = 0;
  for (const b of x) {
    const _ = await fetch(`${l.suiApiUrl}/tokens/receipt`, {
      method: "POST",
      body: JSON.stringify({
        ...u ? { charge_id: u } : {},
        ...a ? { digest: a } : {},
        ...r ? { amount: r } : {},
        ...i ? { currency: i } : {},
        target: b,
        title: e,
        subtitle: n,
        source: ge(w).name
      }),
      headers: {
        Authorization: `Bearer ${$(be)}`,
        "Content-Type": "application/json"
      }
    });
    _.ok ? v++ : console.warn(`Failed to send receipt to ${b}:`, _.status);
  }
  return v > 0;
}, Ve = async ({
  res: u,
  priceCents: e,
  purchaseConfig: a
}) => {
  const n = $(Q), { chain_txs: r, items: i } = u, l = Nt(i);
  It(r, l), J(K.PAYMENT, { type: st.CARD }), J(K.RECHECK_BALANCE);
  const o = $(he);
  o && Ne.track("cp_payment_fiat", {
    $email: o.email,
    $phone: o.phone,
    suiNetwork: n.suiNetwork,
    clientId: n.clientId,
    address: await Be(),
    location: window.location.href,
    assets: a?.assets,
    total: e / 100,
    description: (a?.title ?? "") + `(${a?.subtitle ?? ""})`
  }), await je(), l && pe.set({
    title: "Done!",
    subtitle: "Your payment was partly successful",
    orders: i
  }), ue.set(fe.PAYMENT_RESULT);
}, Bt = async (u) => {
  for (const e of u) {
    const a = await Oe(e?.asset?.packageId);
    let n = null;
    e?.asset?.assetId && (n = await a.CredenzaAssetCollection.getAssetMetadata(+e?.asset?.assetId), e.asset.metadata = n);
  }
};
var Ot = H("<!> <!>", 1);
function Ze(u, e) {
  if (new.target) return ne({ component: Ze, ...u });
  se(e, !1);
  const a = G(), n = G();
  var r = this && this.__awaiter || function(s, c, y, I) {
    function E(L) {
      return L instanceof y ? L : new y(function(B) {
        B(L);
      });
    }
    return new (y || (y = Promise))(function(L, B) {
      function Y(D) {
        try {
          P(I.next(D));
        } catch (z) {
          B(z);
        }
      }
      function V(D) {
        try {
          P(I.throw(D));
        } catch (z) {
          B(z);
        }
      }
      function P(D) {
        D.done ? L(D.value) : E(D.value).then(Y, V);
      }
      P((I = I.apply(s, c || [])).next());
    });
  };
  let i = k(e, "priceCents", 12), l = k(e, "isLoading", 12), o = k(e, "purchaseConfig", 12), w = k(e, "isPriceLoading", 12), x = k(e, "feeToApply", 12, 0);
  const { toastAlert: v } = $(Me), b = $(Q);
  let _, f = G(), h = G(), d, S = G(), g = G(!1);
  we(() => r(void 0, void 0, void 0, function* () {
    var s;
    try {
      if (!_) {
        if (!window.Stripe && (yield He("https://js.stripe.com/v3/"), !window.Stripe))
          throw {};
        _ = window.Stripe;
      }
    } catch {
      return console.log("Please include stripe to use payments.");
    }
    if (t(f)) return;
    const c = ge(b.clientId).name;
    T(f, _((s = b.stripe.pk[c]) !== null && s !== void 0 ? s : b.stripe.pk.DEFAULT)), T(h, t(f).elements()), d = t(h).create("card", { style: Rt }), d.mount("#cpui-card-element"), d.on("change", (y) => {
      T(S, y.complete && !y.error);
    }), d.on("focus", () => T(g, !0)), d.on("blur", () => T(g, !1));
  }));
  const N = () => r(void 0, void 0, void 0, function* () {
    try {
      if (!t(S)) return;
      l(!0);
      const s = yield t(f).createToken(d);
      if (s.error) throw s.error;
      yield m(s.token.id);
    } catch (s) {
      J(K.ERROR, { error: s });
    }
    l(!1);
  }), m = (s) => r(void 0, void 0, void 0, function* () {
    try {
      const { processPayment: c } = yield import("./Stripe.service-CogYS-eH.js"), { assets: y } = o();
      if (!y?.length) throw new Error("No purchase config assets found");
      const I = yield c(s, y);
      yield Ve({
        res: I,
        priceCents: i(),
        purchaseConfig: o()
      });
    } catch (c) {
      v(`Payment error: ${c.message || c}`, "failure"), pe.set({ errorMessage: c.message }), ue.set(fe.ERROR), J(K.ERROR, { error: c });
    }
  });
  ce(
    () => (t(S), q(l()), q(w())),
    () => {
      T(a, !t(S) || l() || w());
    }
  ), ce(() => q(i()), () => {
    T(n, (i() / 100).toFixed(2));
  }), _e();
  var A = {
    get priceCents() {
      return i();
    },
    set priceCents(s) {
      i(s), R();
    },
    get isLoading() {
      return l();
    },
    set isLoading(s) {
      l(s), R();
    },
    get purchaseConfig() {
      return o();
    },
    set purchaseConfig(s) {
      o(s), R();
    },
    get isPriceLoading() {
      return w();
    },
    set isPriceLoading(s) {
      w(s), R();
    },
    get feeToApply() {
      return x();
    },
    set feeToApply(s) {
      x(s), R();
    },
    $set: ie,
    $on: (s, c) => ae(e, s, c)
  };
  ye();
  var C = Ot(), M = le(C);
  {
    let s = ve(() => ({
      isCardFocused: t(g),
      onPay: N,
      feeToApply: x()
    }));
    Ge(M, {
      get options() {
        return t(s);
      },
      get isPaymentDisabled() {
        return t(a);
      },
      set isPaymentDisabled(c) {
        T(a, c);
      },
      get isLoading() {
        return l();
      },
      set isLoading(c) {
        l(c);
      },
      get totalToPay() {
        return t(n);
      },
      set totalToPay(c) {
        T(n, c);
      },
      $$legacy: !0
    });
  }
  var W = U(M, 2);
  {
    var p = (s) => {
      We(s, {
        doPayment: m,
        get stripe() {
          return t(f);
        },
        get stripeElements() {
          return t(h);
        },
        get priceCents() {
          return i();
        },
        get isLoading() {
          return l();
        },
        set isLoading(c) {
          l(c);
        },
        $$legacy: !0
      });
    };
    ee(W, (s) => {
      t(f) && t(h) && s(p);
    });
  }
  return O(u, C), oe(A);
}
function Je(u, e) {
  if (new.target) return ne({ component: Je, ...u });
  se(e, !1);
  const a = () => Pe(ze, "$clientPublicStore", n), [n, r] = De(), i = G();
  var l = this && this.__awaiter || function(m, A, C, M) {
    function W(p) {
      return p instanceof C ? p : new C(function(s) {
        s(p);
      });
    }
    return new (C || (C = Promise))(function(p, s) {
      function c(E) {
        try {
          I(M.next(E));
        } catch (L) {
          s(L);
        }
      }
      function y(E) {
        try {
          I(M.throw(E));
        } catch (L) {
          s(L);
        }
      }
      function I(E) {
        E.done ? p(E.value) : W(E.value).then(c, y);
      }
      I((M = M.apply(m, A || [])).next());
    });
  };
  let o = k(e, "totalPriceToken", 12), w = k(e, "purchaseConfig", 12), x = k(e, "isLoading", 12), v = k(e, "isPriceLoading", 12), b = k(e, "pricesByAsset", 28, () => []);
  const { toastAlert: _ } = $(Me), f = $(Q);
  let h = G(0);
  const d = (m, A) => l(void 0, void 0, void 0, function* () {
    const { type: C, packageId: M, assetId: W, amount: p } = m, s = yield lt(C, M, { assetId: W, amount: p }), { title: c, subtitle: y } = w();
    J(K.PAYMENT), J(K.RECHECK_BALANCE), yield Ye({
      digest: s.digest,
      title: c,
      subtitle: y,
      amount: b()[A],
      currency: "CRED"
    }), J(K.RECEIPT, { digest: s.digest });
  }), S = () => l(void 0, void 0, void 0, function* () {
    var m, A;
    try {
      if (BigInt(o()) > t(h)) return;
      x(!0);
      const { assets: C } = w();
      for (const [W, p] of C.entries())
        yield d(p, W), yield new Promise((s) => setTimeout(s, 1e3));
      const M = $(he);
      M && Ne.track("cp_payment_stored_value", {
        $email: M.email,
        $phone: M.phone,
        suiNetwork: f.suiNetwork,
        clientId: f.clientId,
        location: window.location.href,
        address: yield Be(),
        assets: C,
        total: o(),
        description: ((m = w() === null || w() === void 0 ? void 0 : w().title) !== null && m !== void 0 ? m : "") + `(${(A = w() === null || w() === void 0 ? void 0 : w().subtitle) !== null && A !== void 0 ? A : ""})`
      }), yield je(), ue.set(fe.PAYMENT_RESULT);
    } catch (C) {
      _(`Payment error: ${C.message || C}`, "failure"), pe.set({ errorMessage: C.message }), ue.set(fe.ERROR), J(K.ERROR, { error: C });
    } finally {
      x(!1);
    }
  });
  we(() => l(void 0, void 0, void 0, function* () {
    T(h, Number(yield ct()));
  })), ce(() => (t(h), q(o())), () => {
    T(i, `${(t(h) - o()).toFixed(2)}`);
  }), _e();
  var g = {
    get totalPriceToken() {
      return o();
    },
    set totalPriceToken(m) {
      o(m), R();
    },
    get purchaseConfig() {
      return w();
    },
    set purchaseConfig(m) {
      w(m), R();
    },
    get isLoading() {
      return x();
    },
    set isLoading(m) {
      x(m), R();
    },
    get isPriceLoading() {
      return v();
    },
    set isPriceLoading(m) {
      v(m), R();
    },
    get pricesByAsset() {
      return b();
    },
    set pricesByAsset(m) {
      b(m), R();
    },
    $set: ie,
    $on: (m, A) => ae(e, m, A)
  };
  ye();
  {
    let m = ve(() => (t(i), t(h), a(), q(ue), q(fe), q(o()), q(x()), q(v()), X(() => ({
      formattedBalance: t(i),
      balance: t(h),
      credAlias: a().ui_settings.cred_alias,
      onPay: S,
      onGetCred: () => ue.set(fe.WALLET),
      totalToPay: String(o()),
      isLoading: x(),
      isPaymentDisabled: !Number(t(h)) || o() > t(h) || v()
    }))));
    qe(u, {
      get options() {
        return t(m);
      }
    });
  }
  var N = oe(g);
  return r(), N;
}
const Mt = async (u) => {
  const { assets: e, ...a } = u, n = $t(e), r = await fetch($(Q).credenza.suiApiUrl + "/assets/buy", {
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${$(be)}`
    },
    method: "POST",
    body: JSON.stringify({ ...a, ...n })
  });
  if (!r.ok) throw new Error("Failed to create order");
  const { _id: i } = await r.json();
  return i;
}, zt = async (u) => {
  const e = $(Q), { title: a, subtitle: n } = $(pe), r = await Dt(e.credenza.generalApiUrl, u);
  if (r.items[0].error) throw new Error(r.items[0].error);
  return r.payment_provider_tx && r.payment_provider !== "paystack" && (await Ye({ stripeChargeId: r.payment_provider_tx, title: a, subtitle: n, currency: r.currency }), J(K.RECEIPT, { stripeChargeId: r.payment_provider_tx })), await Bt(r.items), r;
}, $t = (u) => {
  const e = {
    credenza_asset_collection: "collection",
    decom: "decom",
    cred: "coin",
    membership: "membership"
  };
  return u.reduce(
    (n, r) => {
      const i = e[r.type];
      if (!i) return n;
      const l = {
        asset_type: `${r.packageId}::${r.type}::${r.type.toUpperCase()}`
      };
      return r.assetId && (l.asset_id = +r.assetId), r.amount && (l.amount = r.amount), n[i] = n[i] || [], n[i].push(l), n;
    },
    { collection: [], decom: [], coin: [], membership: [] }
  );
};
var jt = H('<span class="crtw-text-xs crtw-text-stone-200"> </span>'), Ft = H('<div class="crtw-w-full crtw-text-center crtw-my-5"><!> <!></div>');
function Ke(u, e) {
  if (new.target) return ne({ component: Ke, ...u });
  se(e, !0);
  var a = this && this.__awaiter || function(d, S, g, N) {
    function m(A) {
      return A instanceof g ? A : new g(function(C) {
        C(A);
      });
    }
    return new (g || (g = Promise))(function(A, C) {
      function M(s) {
        try {
          p(N.next(s));
        } catch (c) {
          C(c);
        }
      }
      function W(s) {
        try {
          p(N.throw(s));
        } catch (c) {
          C(c);
        }
      }
      function p(s) {
        s.done ? A(s.value) : m(s.value).then(M, W);
      }
      p((N = N.apply(d, S || [])).next());
    });
  };
  let n = k(e, "priceCents", 7), r = k(e, "purchaseConfig", 7), i = k(e, "isLoading", 15), l = k(e, "feeToApply", 7), o;
  we(() => a(void 0, void 0, void 0, function* () {
    try {
      o || (window.PaystackPop || (yield He("https://js.paystack.co/v2/inline.js")), o = window.PaystackPop);
    } catch {
      return console.log("Please include paystack to use payments.");
    }
  }));
  const w = (d) => {
    i(!1), $e(`Payment error: ${d.message || d}`, "failure"), pe.set({ errorMessage: d.message }), ue.set(fe.ERROR), J(K.ERROR, { error: d });
  }, x = () => a(void 0, void 0, void 0, function* () {
    var d, S;
    try {
      const { assets: g } = r(), N = $(Q);
      if (!g?.length) throw new Error("No purchase config assets found");
      i(!0);
      const m = ge($(Q).clientId).payment.paystack, A = yield Mt({
        assets: g,
        payment_provider: "paystack",
        client_id: $(Q).clientId,
        currency: m
      }), C = yield St(N.credenza.generalApiUrl, A);
      if (!(!((d = C.payment_provider_data) === null || d === void 0) && d.access_code)) throw new Error("Payment is unavailable now");
      const W = new o().resumeTransaction((S = C.payment_provider_data) === null || S === void 0 ? void 0 : S.access_code);
      W.onSuccess = () => a(void 0, void 0, void 0, function* () {
        try {
          const p = yield zt(A);
          yield Ve({
            res: p,
            priceCents: n(),
            purchaseConfig: r()
          });
        } catch (p) {
          w(p);
        } finally {
          i(!1);
        }
      }), W.onError = (p) => {
        throw i(!1), p;
      }, W.onCancel = () => {
        throw i(!1), new Error("Payment was not finished");
      };
    } catch (g) {
      w(g);
    }
  });
  var v = {
    get priceCents() {
      return n();
    },
    set priceCents(d) {
      n(d), R();
    },
    get purchaseConfig() {
      return r();
    },
    set purchaseConfig(d) {
      r(d), R();
    },
    get isLoading() {
      return i();
    },
    set isLoading(d) {
      i(d), R();
    },
    get feeToApply() {
      return l();
    },
    set feeToApply(d) {
      l(d), R();
    },
    $set: ie,
    $on: (d, S) => ae(e, d, S)
  }, b = Ft(), _ = j(b);
  Le(_, {
    text: "Pay with Mobile Money",
    onClick: x,
    disabled: !1,
    isLoading: !1
  });
  var f = U(_, 2);
  {
    var h = (d) => {
      var S = jt(), g = j(S);
      F(S), re(() => te(g, `Fee of ${l() * 100}% is automatically added.`)), O(d, S);
    };
    ee(f, (d) => {
      l() && d(h);
    });
  }
  return F(b), O(u, b), oe(v);
}
var Ut = H("<!> <!>", 1), Gt = H('<div slot="credit-card"><!> <!></div>'), qt = H('<div slot="cred-balance"><!></div>'), Wt = H("<!> <!>", 1);
function Qe(u, e) {
  if (new.target) return ne({ component: Qe, ...u });
  se(e, !1);
  const a = () => Pe(he, "$userStore", r), n = () => Pe(pe, "$pageOptsStore", r), [r, i] = De();
  var l = this && this.__awaiter || function(c, y, I, E) {
    function L(B) {
      return B instanceof I ? B : new I(function(Y) {
        Y(B);
      });
    }
    return new (I || (I = Promise))(function(B, Y) {
      function V(z) {
        try {
          D(E.next(z));
        } catch (de) {
          Y(de);
        }
      }
      function P(z) {
        try {
          D(E.throw(z));
        } catch (de) {
          Y(de);
        }
      }
      function D(z) {
        z.done ? B(z.value) : L(z.value).then(V, P);
      }
      D((E = E.apply(c, y || [])).next());
    });
  }, o;
  let w = G(!1), x = G(!1), v = [], b = G(0), _ = G(0), f = G(0), h = G(0);
  const d = (o = $(ze).client_payment_configuration) === null || o === void 0 ? void 0 : o.token_fee, S = (c, y, I) => l(void 0, void 0, void 0, function* () {
    if (I && y === ut.CREDENZA_ASSET_COLLECTION)
      return yield ft(c, I);
    const E = yield ke(c), L = yield vt(E), { content: { fields: { price_fiat: B, price_coin: Y } } } = L;
    return [+B, +Y];
  }), g = (c) => l(void 0, void 0, void 0, function* () {
    const y = yield ke(c), { suiNetwork: I } = $(Q), E = yield Oe(c, I), L = yield E.Sellable.getPriceFiat(y, "USD");
    let B = 0;
    return ge($(Q).clientId).payment.paystack && (B = yield E.Sellable.getPriceFiat(y, "GHS")), [L, B];
  }), N = (c) => l(void 0, void 0, void 0, function* () {
    try {
      T(w, !0);
      for (const y of c) {
        const { packageId: I, type: E, amount: L, assetId: B } = y;
        if (`${I}::${E}::${E.toUpperCase()}` === dt() && L) {
          const [V, P] = yield g(I);
          T(b, t(b) + L * V), T(_, t(_) + L * P), d && (T(h, d), T(b, t(b) + t(b) * d), T(_, t(_) + t(_) * d));
        } else {
          let [V, P] = yield S(I, E, B);
          L && L !== 0 && (V *= L, P *= L), T(b, t(b) + V), T(f, t(f) + P / Te), v.push(P / Te);
        }
      }
    } catch (y) {
      console.log(y), $e("Error calculating the price", "failure"), J(K.ERROR, y);
    } finally {
      T(w, !1);
    }
  }), m = pe.subscribe((c) => l(void 0, void 0, void 0, function* () {
    !c?.assets || !c.assets.length || (yield N(c.assets));
  }));
  it(m);
  var A = {
    $set: ie,
    $on: (c, y) => ae(e, c, y)
  };
  ye();
  var C = Wt(), M = le(C);
  {
    var W = (c) => {
      var y = xe(), I = le(y);
      pt(I, () => import("./ProgressVideo-f0nY6lio.js"), null, (E, L) => {
        var B = xe(), Y = le(B);
        at(Y, () => t(L).default, (V, P) => {
          P(V, {});
        }), O(E, B);
      }), O(c, y);
    };
    ee(M, (c) => {
      t(x) && c(W);
    });
  }
  var p = U(M, 2);
  {
    let c = ve(() => ({
      user: a(),
      title: n().title || "Order Summary",
      subtitle: n().subtitle,
      onBackClick: () => ue.set(fe.WALLET),
      isCardDisabled: n().payments?.card?.disabled,
      isCredezaValueDisabled: !t(b) || n().payments?.credenzaStoredValue?.disabled
    }));
    Ue(p, {
      get options() {
        return t(c);
      },
      get isLoading() {
        return t(x);
      },
      set isLoading(y) {
        T(x, y);
      },
      $$slots: {
        "credit-card": (y, I) => {
          var E = Gt(), L = j(E);
          {
            var B = (D) => {
              Ze(D, {
                get priceCents() {
                  return t(b);
                },
                get isPriceLoading() {
                  return t(w);
                },
                get purchaseConfig() {
                  return n();
                },
                get feeToApply() {
                  return t(h);
                },
                get isLoading() {
                  return t(x);
                },
                set isLoading(z) {
                  T(x, z);
                },
                $$legacy: !0
              });
            };
            ee(L, (D) => {
              t(b) && D(B);
            });
          }
          var Y = U(L, 2);
          {
            var V = (D) => {
              var z = Ut(), de = le(z);
              Fe(de, {});
              var Xe = U(de, 2);
              Ke(Xe, {
                get priceCents() {
                  return t(_);
                },
                get purchaseConfig() {
                  return n();
                },
                get feeToApply() {
                  return t(h);
                },
                get isLoading() {
                  return t(x);
                },
                set isLoading(et) {
                  T(x, et);
                },
                $$legacy: !0
              }), O(D, z);
            }, P = Ee(() => ge($(Q).clientId).payment.paystack);
            ee(Y, (D) => {
              t(P) && D(V);
            });
          }
          F(E), O(y, E);
        },
        "cred-balance": (y, I) => {
          var E = qt(), L = j(E);
          Je(L, {
            get pricesByAsset() {
              return v;
            },
            get totalPriceToken() {
              return t(f);
            },
            get isPriceLoading() {
              return t(w);
            },
            get purchaseConfig() {
              return n();
            },
            get isLoading() {
              return t(x);
            },
            set isLoading(B) {
              T(x, B);
            },
            $$legacy: !0
          }), F(E), O(y, E);
        }
      },
      $$legacy: !0
    });
  }
  O(u, C);
  var s = oe(A);
  return i(), s;
}
const tr = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Qe
}, Symbol.toStringTag, { value: "Module" }));
export {
  tr as P,
  Mt as c,
  zt as p
};
//# sourceMappingURL=Payment-DgTh_h7z.js.map
