import e, { useCallback as ee, useEffect as L, useState as ye } from "react";
import { P as k, a as U, b as G, c as ge, I as Ce, d as De, A as Pe } from "./index-03fe2d8e.mjs";
import { e as Qt } from "./index-03fe2d8e.mjs";
import { A as Ae } from "./Alert-98fe02c6.mjs";
import { e as te, h as Le, B as J, b as Te, a as Ie } from "./useRoutes-367960a3.mjs";
import { C as j } from "./CommonError-b56f12ad.mjs";
import { a as ne, u as he, d as _e, D as we, b as Re, c as be } from "./index-28007ca6.mjs";
import { a as ve } from "./LoadingPage-d6d2cc0b.mjs";
import { A as Y } from "./Alert-1277e378.mjs";
import { P as f } from "./EcommTypes-beac1085.mjs";
import { DesktopChecker as y, UrlHelper as q } from "@accelbyte/sdk";
import { format as Ue, parseISO as ke } from "date-fns";
import { Trans as C } from "react-i18next";
import { C as re } from "./CommonError-55bf3e5d.mjs";
import { I as X, O as Me } from "./OrdersHooks-860eeb0d.mjs";
import { d as Fe, A as z, c as xe, F as Q, b as x } from "./Env-92498313.mjs";
import Ye from "classnames";
import { u as $e, P as R } from "./usePayment-32ac9b6e.mjs";
import { P as V, a as Be, b as He, c as We, O as Ke, d as Ge } from "./PaymentStatusDialog-0ad5b34a.mjs";
import { z as ae } from "zod";
import { u as Je } from "./usePendingOrders-515ff6cf.mjs";
import { u as je, a as qe } from "./useOrderProcess-555cab8c.mjs";
import { OrderStatus as O } from "@accelbyte/sdk-platform";
import "./Checkbox-001b1e04.mjs";
import "./InputGroup-b546018b.mjs";
import "react-tooltip";
import "./InputLabel-760cfc94.mjs";
import "frames-react";
import "prop-types";
import "./FetchUtils-17af17dc.mjs";
import "./InfoIcon-c86fd057.mjs";
import "react-feather";
import "flat";
import "i18next";
import "./utils.mjs";
import "uuid";
import "./ErrorLayout-d232f96c.mjs";
import "@accelbyte/sdk-legal";
import "react-dom";
import "buffer";
import "react-toastify";
import "@accelbyte/sdk-gdpr";
import "@accelbyte/sdk-iam";
import "@accelbyte/sdk-basic";
import "axios";
import "./ArrowIcon-afdb4626.mjs";
import "./index-35107a02.mjs";
const Z = "payment-station-iframe";
function Xe({ onPaymentProcessed: n, returnUrl: s, className: a, order: i, paymentStationUrl: u }) {
  const {
    state: { paymentStationMessage: P },
    mutations: { setPaymentStationMessage: A }
  } = $e(), c = ee(
    (o) => {
      const S = y.isDesktopApp() && o ? o.data : P;
      if (S)
        try {
          const N = k.extractPaymentResult(S);
          if (N)
            switch (N.paymentStatus) {
              case f.enum.DONE:
                n(N.paymentStatus);
                break;
              case f.enum.FAILED:
                n(N.paymentStatus);
                break;
            }
        } catch (N) {
          console.error(N);
        }
    },
    [P]
  ), { state: r } = te();
  L(c, [P]), L(() => (y.isDesktopApp() && (window.addEventListener("message", c), Device.receive(X.OPEN_URL, (o) => {
    const S = new URL(o), N = S.search, M = S.pathname.split("/").filter((h) => h !== "").join("/"), l = new URLSearchParams(S.search).get("paymentStatus");
    l === f.enum.DONE && n(f.enum.DONE), l === f.enum.FAILED && n(f.enum.FAILED), r.replace(`/${M}${N}`);
  }), window.addEventListener("message", c)), () => {
    y.isDesktopApp() && (window.removeEventListener("message", c), Device.remove(X.OPEN_URL));
  }), [c]);
  const m = new URLSearchParams(window.location.search).get("paymentStatus");
  L(() => {
    if (!y.isDesktopApp()) {
      if (m === U.enum.DONE) {
        window.opener && window.opener.postMessage(JSON.stringify({ message: { action: R.enum.complete } }), "*"), A({ message: { action: R.enum.complete } });
        const o = `${s}?paymentStatus=${m}`;
        k.redirectToUrlIfExist(o);
      } else if (m === U.enum.CANCELLED) {
        window.opener && window.opener.postMessage(JSON.stringify({ message: { action: R.enum.cancel } }), "*"), A({ message: { action: R.enum.cancel } });
        const o = `${s}?paymentStatus=${m}`;
        k.redirectToUrlIfExist(o);
      }
    }
  }, [m]);
  const [g] = Fe(), p = g.namespace;
  return y.isDesktopApp() ? /* @__PURE__ */ e.createElement(ze, { returnUrl: s, className: a, order: i, paymentStationUrl: u }) : m === U.enum.DONE ? /* @__PURE__ */ e.createElement(G, { type: Y.success, message: "Payment Success" }) : m === U.enum.CANCELLED ? /* @__PURE__ */ e.createElement(G, { type: Y.info, message: "Payment Cancelled" }) : i != null && i.paymentOrderNo ? /* @__PURE__ */ e.createElement(ge, { paymentOrderNo: i.paymentOrderNo, namespace: p, returnUrl: s }) : /* @__PURE__ */ e.createElement("div", { className: "errorContainer" }, /* @__PURE__ */ e.createElement(re, { error: new Error("Invalid request: paymentOrderNo is required") }));
}
function ze({
  paymentStationUrl: n,
  order: s,
  returnUrl: a,
  className: i
}) {
  const {
    state: { discoveryConfigData: u }
  } = ne(), {
    state: { launcherData: P }
  } = he(), {
    tokens: { accessToken: A }
  } = _e();
  L(() => (window.addEventListener("message", c), () => {
    window.removeEventListener("message", c);
  }), []);
  const c = (g) => {
    const p = g && g.data;
    if (p)
      try {
        const o = k.isStringJson(p) && JSON.parse(p);
        if ((o == null ? void 0 : o.action) === R.enum.requestData && n) {
          m(n);
          return;
        }
      } catch (o) {
        console.error(o);
      }
  }, r = Qe({ paymentStationUrl: n, order: s, returnUrl: a });
  if (!r)
    return /* @__PURE__ */ e.createElement("div", { className: "errorContainer" }, /* @__PURE__ */ e.createElement(re, { error: new Error() }));
  function b() {
    y.isDesktopApp() && n && m(n);
  }
  const m = (g) => {
    const p = JSON.stringify({
      accessToken: A,
      config: P,
      globalPageConfig: u,
      channel: Ce
    }), o = document.getElementById(Z).contentWindow;
    if (!o)
      return console.log("Message to iframe window ignored");
    o.postMessage(p, g);
  };
  return /* @__PURE__ */ e.createElement(
    "iframe",
    {
      onLoad: b,
      id: Z,
      className: Ye("paymentStation", i),
      title: "Pay station",
      src: r,
      sandbox: De
    }
  );
}
function Qe(n) {
  try {
    const { order: s, paymentStationUrl: a, returnUrl: i } = n, u = new URL(a || s && s.paymentStationUrl || "");
    return u.searchParams.append("returnUrl", i), u.searchParams.append("parentAppName", y.isDesktopApp() ? z.LAUNCHER : z.PP), s != null && s.paymentOrderNo && u.searchParams.append("paymentOrderNo", s.paymentOrderNo), u.toString();
  } catch {
    return null;
  }
}
const Ve = 5, Ze = 1e3, w = ae.enum(["CANCELLATION_PROMPT", "CANCELLATION_SUCCESS"]), D = ae.enum(["PAYMENT_NEED_MORE_PROCESSING_TIME", "PAYMENT_PROCESSED_COUNTDOWN", "PAYMENT_SUCCESSFUL"]);
function et({ orderNo: n, isOnlyShowCloseButton: s, onClosePaymentDialog: a, redirectPath: i }) {
  const [u, P] = ye({
    paymentStatus: null,
    orderInfo: null,
    currentlyOpenDialog: void 0
  }), {
    state: { flags: A }
  } = ne(), {
    state: { user: c }
  } = xe(), {
    state: { order: r, orderFetchStatus: b, orderError: m, isOrderExpired: g },
    mutations: { fetchOrder: p }
  } = Me.useOrderDetail(), {
    state: { cancelProcessFetchStatus: o, cancelProcessError: S },
    mutations: { cancelAllPendingOrders: N, resetState: M }
  } = Je(), {
    mutations: { refreshWallet: $ }
  } = je(), l = c == null ? void 0 : c.userId;
  L(() => {
    l && p({ userId: l, orderNo: n });
  }, [l, n]);
  const h = ee((t) => {
    t.preventDefault();
  }, []);
  L(() => (window.addEventListener("beforeunload", h, !1), () => {
    window.removeEventListener("beforeunload", h, !1), M();
  }), []);
  const { state: F } = te();
  function v() {
    if (i) {
      F.push(i);
      return;
    }
    return null;
  }
  function E(t) {
    P((d) => ({ ...d, ...t }));
  }
  function se() {
    E({ currentlyOpenDialog: void 0 });
  }
  function oe() {
    const t = o === Q.CANCELLING;
    return /* @__PURE__ */ e.createElement(
      we,
      {
        className: "orderDialog",
        title: /* @__PURE__ */ e.createElement(C, { i18nKey: "OrderPage.cancellationDialog.title" }, "Confirm Cancellation"),
        isOpen: !0
      },
      /* @__PURE__ */ e.createElement(Re, null, /* @__PURE__ */ e.createElement("p", null, /* @__PURE__ */ e.createElement(C, { i18nKey: "OrderPage.cancellationDialog.message" }, "You're just one step away from completing payment, are you sure you want to cancel this order?")), S && /* @__PURE__ */ e.createElement("div", { className: "errorContainer" }, /* @__PURE__ */ e.createElement(j, { error: S }))),
      /* @__PURE__ */ e.createElement(be, { className: "orderCancellationDialogFooter" }, /* @__PURE__ */ e.createElement("div", { className: "btnContainer" }, /* @__PURE__ */ e.createElement(
        J,
        {
          disabled: t,
          onClick: se,
          className: "btn btn-ghost uppercase",
          buttonType: Te.TEXT,
          buttonStyle: Ie.NONE
        },
        /* @__PURE__ */ e.createElement(C, { i18nKey: "OrderPage.cancellationDialog.backButton" }, "Back")
      ), /* @__PURE__ */ e.createElement(J, { loadingIndicator: "SPINNER", className: "btn-primary uppercase", isLoading: t, onClick: () => le() }, /* @__PURE__ */ e.createElement(C, { i18nKey: "OrderPage.cancellationDialog.cancelButton" }, "Cancel Order"))))
    );
  }
  function ie() {
    if (!r)
      return null;
    if (!(r.status !== O.enum.CLOSED && !g))
      return /* @__PURE__ */ e.createElement(Ke, { className: "orderDialog", onCloseDialog: v });
  }
  function B() {
    v(), r && (a == null || a({ status: "payment-succeeded", order: r }));
  }
  function ce() {
    a == null || a({ status: "orders-cancelled" }), v();
  }
  function me() {
    return /* @__PURE__ */ e.createElement(Ge, { className: "orderDialog", onCloseDialog: ce });
  }
  async function le() {
    if (!r || !l)
      return;
    (await N([r], l)).error || E({
      currentlyOpenDialog: w.enum.CANCELLATION_SUCCESS
    });
  }
  async function ue() {
    var d;
    if (!l)
      return;
    const t = await p({ orderNo: n, userId: l });
    if (await $(c, A), E({ paymentStatus: f.enum.DONE }), !!((d = t.data) != null && d.order))
      switch (t.data.order.status) {
        case O.enum.INIT:
          H(), E({
            currentlyOpenDialog: D.enum.PAYMENT_PROCESSED_COUNTDOWN
          });
          break;
        case O.enum.CHARGED:
        case O.enum.FULFILLED:
          E({
            currentlyOpenDialog: D.enum.PAYMENT_SUCCESSFUL
          });
          break;
      }
  }
  async function H(t = Ve, d = Ze) {
    var K;
    if (!l)
      return;
    const I = (K = (await p({ orderNo: n, userId: l })).data) == null ? void 0 : K.order;
    I && (I.status === O.enum.FULFILLED && (window.removeEventListener("beforeunload", h, !1), E({
      currentlyOpenDialog: D.enum.PAYMENT_SUCCESSFUL
    }), a == null || a({ status: "payment-succeeded", order: I })), I.status === O.enum.INIT && t > 0 && setTimeout(() => {
      H(t - 1, d);
    }, d), t === 0 && (E({
      currentlyOpenDialog: D.enum.PAYMENT_NEED_MORE_PROCESSING_TIME
    }), a == null || a({ status: "payment-processing" })));
  }
  const {
    mutations: { onOrderFulfilledHook: pe }
  } = qe(), { state: Ee } = Le();
  function de(t) {
    const d = `${q.trimSlashFromStringStart(F.location.pathname)}${F.location.search}`;
    return /* @__PURE__ */ e.createElement(
      Xe,
      {
        order: t,
        onPaymentProcessed: (_) => {
          switch (_) {
            case f.enum.DONE:
              pe({ user: c, flags: A, createdOrder: t }), ue();
              break;
            case f.enum.FAILED:
              E({ paymentStatus: _ });
              break;
          }
        },
        paymentStationUrl: y.isDesktopApp() ? x.LAUNCHER_PAYMENT_URL : void 0,
        returnUrl: y.isDesktopApp() ? `${x.REDIRECT_URL}${d}` : q.combineURLPaths(window.location.origin, x.PLAYER_PORTAL_BASE_URL, Ee.paymentSuccessCallback.link)
      }
    );
  }
  function fe(t, d) {
    if (!t.expireTime)
      return;
    const { paymentStatus: _ } = u, I = Ue(ke(t.expireTime), "d MMM yyyy hh:mm a");
    return /* @__PURE__ */ e.createElement("div", { className: "orderContent" }, /* @__PURE__ */ e.createElement("div", { className: "orderCard" }, /* @__PURE__ */ e.createElement("div", { className: "orderHeader" }, /* @__PURE__ */ e.createElement(C, { i18nKey: "OrderPage.orderContent.title" }, "Payment")), /* @__PURE__ */ e.createElement("div", { className: "orderExpire" }, d.regionDataItem && /* @__PURE__ */ e.createElement(Ae, { type: Y.info }, /* @__PURE__ */ e.createElement(C, { i18nKey: "OrderPage.orderExpire.title" }, "This order will expire on"), " ", I)), t && t.status === O.enum.INIT && _ !== f.enum.DONE && /* @__PURE__ */ e.createElement("section", { className: "paymentSection", id: "paymentSection" }, de(t), /* @__PURE__ */ e.createElement("div", { className: "btnContainer" }, /* @__PURE__ */ e.createElement(
      "button",
      {
        disabled: t.status !== O.enum.INIT,
        onClick: () => E({
          currentlyOpenDialog: w.enum.CANCELLATION_PROMPT
        }),
        className: "btn btn-ghost"
      },
      /* @__PURE__ */ e.createElement(C, { i18nKey: "OrderPage.cancelOrder" }, "Cancel")
    )))), /* @__PURE__ */ e.createElement(
      "button",
      {
        disabled: t.status !== O.enum.INIT,
        onClick: () => E({
          currentlyOpenDialog: w.enum.CANCELLATION_PROMPT
        }),
        className: "btn btnCancel"
      },
      /* @__PURE__ */ e.createElement(C, { i18nKey: "OrderPage.cancelOrder" }, "Cancel")
    ));
  }
  function Ne() {
    E({ paymentStatus: null, currentlyOpenDialog: void 0 });
  }
  const { paymentStatus: Oe, currentlyOpenDialog: T } = u, Se = D.safeParse(T).success, W = b === Q.FETCHING;
  return (r == null ? void 0 : r.status) === O.enum.FULFILLED ? /* @__PURE__ */ e.createElement(
    V,
    {
      className: "orderDialog",
      orderInfo: r,
      onCloseDialog: B,
      isOnlyShowCloseButton: s
    }
  ) : /* @__PURE__ */ e.createElement("div", { className: "paymentBox h-full" }, T === D.enum.PAYMENT_NEED_MORE_PROCESSING_TIME && /* @__PURE__ */ e.createElement(Be, { onClose: v }), T === D.enum.PAYMENT_PROCESSED_COUNTDOWN && /* @__PURE__ */ e.createElement(He, null), T === D.enum.PAYMENT_SUCCESSFUL && r && /* @__PURE__ */ e.createElement(
    V,
    {
      className: "orderDialog",
      orderInfo: r,
      onCloseDialog: B,
      isOnlyShowCloseButton: s
    }
  ), Oe === f.enum.FAILED && /* @__PURE__ */ e.createElement(We, { className: "orderDialog", onCloseDialog: () => Ne() }), ie(), T === w.enum.CANCELLATION_SUCCESS && me(), T === w.enum.CANCELLATION_PROMPT && oe(), W && /* @__PURE__ */ e.createElement("div", { className: "flex h-full items-center justify-center" }, /* @__PURE__ */ e.createElement(ve, null)), !W && /* @__PURE__ */ e.createElement(e.Fragment, null, m && /* @__PURE__ */ e.createElement("div", { className: "errorContainer" }, /* @__PURE__ */ e.createElement(j, { error: m })), (r == null ? void 0 : r.itemSnapshot) && !Se && fe(r, r.itemSnapshot)));
}
function tt(n) {
  return /* @__PURE__ */ e.createElement("main", { className: "orderDetailPage" }, /* @__PURE__ */ e.createElement(et, { ...n }));
}
function qt({ paymentOrderNo: n, namespace: s, ...a }) {
  return L(() => {
    const i = document.createElement("script");
    return i.src = "https://cdn.checkout.com/js/framesv2.min.js", i.async = !0, document.body.appendChild(i), () => {
      document.body.removeChild(i);
    };
  }, []), /* @__PURE__ */ e.createElement(Pe.Provider, { value: { namespace: s, paymentOrderNo: n } }, /* @__PURE__ */ e.createElement(tt, { ...a, orderNo: n }));
}
export {
  Qt as PaymentForIframe,
  qt as PaymentWidget
};
