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 "./PaymentForIframe-78e48786.mjs";
import { e as rr } from "./PaymentForIframe-78e48786.mjs";
import { A as Ae } from "./Alert-1fab9453.mjs";
import { B as J, b as Le, c as Te } from "./Button-c97a7217.mjs";
import { C as j } from "./CommonError-e27d39d7.mjs";
import { D as Ie, a as he, b as _e } from "./Dialog-806d50a9.mjs";
import { L as we } from "./Loading-9dff8957.mjs";
import { A as Y } from "./Alert-1277e378.mjs";
import { b as f } from "./FetchUtils-cc53dbb5.mjs";
import { DesktopChecker as y, UrlHelper as q } from "@accelbyte/sdk";
import { format as Re, parseISO as be } from "date-fns";
import { Trans as C } from "react-i18next";
import { C as te } from "./CommonError-67040eba.mjs";
import { I as X, O as ve } from "./OrdersHooks-14e67720.mjs";
import { a as Ue, A as z, b as ke, F as Q } from "./FetchConfigsUtils-476a602b.mjs";
import Me from "classnames";
import { u as Fe, P as R } from "./usePayment-a352d068.mjs";
import { a as xe } from "./useAppState-80c04995.mjs";
import { u as Ye } from "./useAppConfigs-0fb5df89.mjs";
import { u as re } from "./useDiscoveryConfigs-cf63cd60.mjs";
import { a as ne, u as $e } from "./useUserInfo-ad7006e5.mjs";
import { a as Be, u as He, P as V, b as We, c as Ke, d as Ge, O as Je, e as je } from "./PaymentStatusDialog-26c106f3.mjs";
import { z as ae } from "zod";
import { u as qe } from "./usePendingOrders-53ca2538.mjs";
import { E as x } from "./Env-161a418e.mjs";
import { OrderStatus as O } from "@accelbyte/sdk-platform";
import "./ConfigsUtils-dd5e59d2.mjs";
import "./Checkbox-c1d65bdf.mjs";
import "./InputGroup-8377b80f.mjs";
import "react-tooltip";
import "./InputLabel-760cfc94.mjs";
import "frames-react";
import "prop-types";
import "./InfoIcon-c86fd057.mjs";
import "react-feather";
import "flat";
import "i18next";
import "./SSRHelper-8eb361ff.mjs";
import "react-dom";
import "./starBgGradient-589e5185.mjs";
import "./RouteUtils-f2d71427.mjs";
import "uuid";
import "axios";
import "@accelbyte/sdk-iam";
import "@accelbyte/sdk-gdpr";
import "@accelbyte/sdk-legal";
import "@accelbyte/sdk-basic";
import "./ArrowIcon-7c2378f0.mjs";
import "./i18n-6228a4ed.mjs";
import "./index-0462597a.mjs";
import "./widget-ctx-5e46828e.mjs";
const Z = "payment-station-iframe";
function Xe({ onPaymentProcessed: r, returnUrl: s, className: a, order: i, paymentStationUrl: u }) {
  const {
    state: { paymentStationMessage: P },
    mutations: { setPaymentStationMessage: A }
  } = Fe(), 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:
                r(N.paymentStatus);
                break;
              case f.enum.FAILED:
                r(N.paymentStatus);
                break;
            }
        } catch (N) {
          console.error(N);
        }
    },
    [P]
  ), { state: n } = ne();
  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 && r(f.enum.DONE), l === f.enum.FAILED && r(f.enum.FAILED), n.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] = Ue(), 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(te, { error: new Error("Invalid request: paymentOrderNo is required") }));
}
function ze({
  paymentStationUrl: r,
  order: s,
  returnUrl: a,
  className: i
}) {
  const {
    state: { discoveryConfigData: u }
  } = re(), {
    state: { launcherData: P }
  } = Ye(), {
    tokens: { accessToken: A }
  } = xe();
  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 && r) {
          m(r);
          return;
        }
      } catch (o) {
        console.error(o);
      }
  }, n = Qe({ paymentStationUrl: r, order: s, returnUrl: a });
  if (!n)
    return /* @__PURE__ */ e.createElement("div", { className: "errorContainer" }, /* @__PURE__ */ e.createElement(te, { error: new Error() }));
  function b() {
    y.isDesktopApp() && r && m(r);
  }
  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: Me("paymentStation", i),
      title: "Pay station",
      src: n,
      sandbox: De
    }
  );
}
function Qe(r) {
  try {
    const { order: s, paymentStationUrl: a, returnUrl: i } = r, 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: r, isOnlyShowCloseButton: s, onClosePaymentDialog: a, redirectPath: i }) {
  const [u, P] = ye({
    paymentStatus: null,
    orderInfo: null,
    currentlyOpenDialog: void 0
  }), {
    state: { flags: A }
  } = re(), {
    state: { user: c }
  } = $e(), {
    state: { order: n, orderFetchStatus: b, orderError: m, isOrderExpired: g },
    mutations: { fetchOrder: p }
  } = ve.useOrderDetail(), {
    state: { cancelProcessFetchStatus: o, cancelProcessError: S },
    mutations: { cancelAllPendingOrders: N, resetState: M }
  } = qe(), {
    mutations: { refreshWallet: $ }
  } = Be(), l = c == null ? void 0 : c.userId;
  L(() => {
    l && p({ userId: l, orderNo: r });
  }, [l, r]);
  const h = ee((t) => {
    t.preventDefault();
  }, []);
  L(() => (window.addEventListener("beforeunload", h, !1), () => {
    window.removeEventListener("beforeunload", h, !1), M();
  }), []);
  const { state: F } = ne();
  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(
      Ie,
      {
        className: "orderDialog",
        title: /* @__PURE__ */ e.createElement(C, { i18nKey: "OrderPage.cancellationDialog.title" }, "Confirm Cancellation"),
        isOpen: !0
      },
      /* @__PURE__ */ e.createElement(he, 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(_e, { className: "orderCancellationDialogFooter" }, /* @__PURE__ */ e.createElement("div", { className: "btnContainer" }, /* @__PURE__ */ e.createElement(
        J,
        {
          disabled: t,
          onClick: se,
          className: "btn btn-ghost uppercase",
          buttonType: Le.TEXT,
          buttonStyle: Te.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 (!n)
      return null;
    if (!(n.status !== O.enum.CLOSED && !g))
      return /* @__PURE__ */ e.createElement(Je, { className: "orderDialog", onCloseDialog: v });
  }
  function B() {
    v(), n && (a == null || a({ status: "payment-succeeded", order: n }));
  }
  function ce() {
    a == null || a({ status: "orders-cancelled" }), v();
  }
  function me() {
    return /* @__PURE__ */ e.createElement(je, { className: "orderDialog", onCloseDialog: ce });
  }
  async function le() {
    if (!n || !l)
      return;
    (await N([n], l)).error || E({
      currentlyOpenDialog: w.enum.CANCELLATION_SUCCESS
    });
  }
  async function ue() {
    var d;
    if (!l)
      return;
    const t = await p({ orderNo: r, 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: r, 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 }
  } = He(), { state: Ee } = ke();
  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 = Re(be(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 (n == null ? void 0 : n.status) === O.enum.FULFILLED ? /* @__PURE__ */ e.createElement(
    V,
    {
      className: "orderDialog",
      orderInfo: n,
      onCloseDialog: B,
      isOnlyShowCloseButton: s
    }
  ) : /* @__PURE__ */ e.createElement("div", { className: "paymentBox h-full" }, T === D.enum.PAYMENT_NEED_MORE_PROCESSING_TIME && /* @__PURE__ */ e.createElement(We, { onClose: v }), T === D.enum.PAYMENT_PROCESSED_COUNTDOWN && /* @__PURE__ */ e.createElement(Ke, null), T === D.enum.PAYMENT_SUCCESSFUL && n && /* @__PURE__ */ e.createElement(
    V,
    {
      className: "orderDialog",
      orderInfo: n,
      onCloseDialog: B,
      isOnlyShowCloseButton: s
    }
  ), Oe === f.enum.FAILED && /* @__PURE__ */ e.createElement(Ge, { 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(we, null)), !W && /* @__PURE__ */ e.createElement(e.Fragment, null, m && /* @__PURE__ */ e.createElement("div", { className: "errorContainer" }, /* @__PURE__ */ e.createElement(j, { error: m })), (n == null ? void 0 : n.itemSnapshot) && !Se && fe(n, n.itemSnapshot)));
}
function tt(r) {
  return /* @__PURE__ */ e.createElement("main", { className: "orderDetailPage" }, /* @__PURE__ */ e.createElement(et, { ...r }));
}
function Zt({ paymentOrderNo: r, 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: r } }, /* @__PURE__ */ e.createElement(tt, { ...a, orderNo: r }));
}
export {
  rr as PaymentForIframe,
  Zt as PaymentWidget
};
