import { CommonError as y } from "./accelbyte-widgets204.mjs";
import A from "./accelbyte-widgets210.mjs";
import { PaymentAlert as d } from "./accelbyte-widgets493.mjs";
import { IFRAME_CHANNEL as w, PaymentStatusType as f } from "./accelbyte-widgets494.mjs";
import D from "./accelbyte-widgets495.mjs";
import { PAYMENT_STATION_ACTION as u, sendMessageToParentWindow as h } from "./accelbyte-widgets496.mjs";
import { redirectToUrlIfExist as S } from "./accelbyte-widgets497.mjs";
import { IpcChannels as g } from "./accelbyte-widgets148.mjs";
import { AppName as P } from "./accelbyte-widgets78.mjs";
import { Ctx as p } from "./accelbyte-widgets33.mjs";
import { AlertType as E } from "./accelbyte-widgets128.mjs";
import { PaymentStatus as o } from "./accelbyte-widgets185.mjs";
import O from "classnames";
import { DesktopChecker as l } from "@accelbyte/sdk";
import i from "react";
import * as I from "uuid";
import { z as k } from "zod";
var c;
const N = k.enum(["paymentSuccess", "paymentGenericError"]), X = A(
  (c = class extends i.Component {
    constructor(t) {
      super(t), this.onIframeLoaded = () => {
        const { paymentStationUrl: e } = this.props;
        l.isDesktopApp() && e && this.sendDataToIframe(e);
      }, this.sendDataToIframe = (e) => {
        const a = JSON.stringify({
          accessToken: p.getAppState().db.getAccessToken(),
          config: p.getAppState().getConfig(),
          globalPageConfig: p.getAppState().getGlobalPageConfigFromDiscovery(),
          discoveryConfig: p.getAppState().state.discovery,
          channel: w
        }), n = document.getElementById(c.IFRAME_ID).contentWindow;
        if (!n)
          return console.log("Message to iframe window ignored");
        n.postMessage(a, e);
      }, this.extractPaymentResult = (e) => {
        try {
          if (this.isStringJson(e)) {
            const a = JSON.parse(e);
            if (a.action === "complete" || a.paymentStatus)
              return {
                orderNo: "",
                paymentStatus: o.enum.DONE
              };
            if (!!a.type && a.type === "paymentStationEvent") {
              const r = !!a.event.name && a.event.name;
              let s = null;
              switch (r) {
                case N.enum.paymentSuccess:
                  s = { orderNo: a.event.orderNo, paymentStatus: o.enum.DONE };
                  break;
                case N.enum.paymentGenericError:
                  s = { orderNo: a.event.orderNo, paymentStatus: o.enum.FAILED };
                  break;
              }
              return s;
            }
          }
          return null;
        } catch (a) {
          return console.error(a), {
            orderNo: "",
            paymentStatus: o.enum.FAILED
          };
        }
      }, this.reloadIframe = () => {
        this.setState({ iframeKey: I.v4() });
      }, this.listenToPaymentCallback = (e) => {
        const { onPaymentProcessed: a, paymentStationUrl: n } = this.props, m = l.isDesktopApp() && e ? e.data : this.paymentMethodAppManager.state.paymentStationMessage;
        if (m)
          try {
            const r = this.isStringJson(m) && JSON.parse(m);
            if ((r == null ? void 0 : r.action) === u.enum.requestData && n) {
              this.sendDataToIframe(n);
              return;
            }
            const s = this.extractPaymentResult(m);
            if (s)
              switch (s.paymentStatus) {
                case o.enum.DONE:
                  a(s.paymentStatus);
                  break;
                case o.enum.FAILED:
                  a(s.paymentStatus);
                  break;
              }
          } catch (r) {
            console.error(r);
          }
      }, this.renderDeskPaymentStation = () => {
        const e = this.getPaymentStationUrl();
        return e ? /* @__PURE__ */ i.createElement(
          "iframe",
          {
            onLoad: this.onIframeLoaded,
            id: c.IFRAME_ID,
            key: this.state.iframeKey,
            className: O("paymentStation", this.props.className),
            title: "Pay station",
            src: e,
            sandbox: c.IFRAME_SANDBOX_OPTIONS
          }
        ) : /* @__PURE__ */ i.createElement("div", { className: "errorContainer" }, /* @__PURE__ */ i.createElement(y, { error: new Error() }));
      }, this.state = {
        iframeKey: "0"
      }, this.paymentMethodAppManager = p.getAppState().paymentMethodManager;
    }
    componentDidMount() {
      this.paymentMethodAppManager.subscribe(this.listenToPaymentCallback), l.isDesktopApp() && (window.addEventListener("message", this.listenToPaymentCallback), Device.receive(g.OPEN_URL, (t) => {
        const e = new URL(t), a = e.search, n = e.pathname.split("/").filter((s) => s !== "").join("/"), r = new URLSearchParams(e.search).get("paymentStatus");
        r === o.enum.DONE && this.props.onPaymentProcessed(o.enum.DONE), r === o.enum.FAILED && this.props.onPaymentProcessed(o.enum.FAILED), p.getAppState().state.appHistory.replace(`/${n}${a}`);
      }));
    }
    componentWillUnmount() {
      this.paymentMethodAppManager.unsubscribe(this.listenToPaymentCallback), l.isDesktopApp() && (window.removeEventListener("message", this.listenToPaymentCallback), Device.remove(g.OPEN_URL));
    }
    getPaymentStationUrl() {
      try {
        const { order: t, paymentStationUrl: e, returnUrl: a } = this.props, n = new URL(e || t && t.paymentStationUrl || "");
        return n.searchParams.append("returnUrl", a), n.searchParams.append("parentAppName", l.isDesktopApp() ? P.LAUNCHER : P.PP), t != null && t.paymentOrderNo && n.searchParams.append("paymentOrderNo", t.paymentOrderNo), n.toString();
      } catch {
        return null;
      }
    }
    isStringJson(t) {
      try {
        JSON.parse(t);
      } catch {
        return !1;
      }
      return !0;
    }
    render() {
      const { order: t, returnUrl: e } = this.props, n = new URLSearchParams(window.location.search).get("paymentStatus"), m = p.getAppState().sdkOptions.namespace;
      if (l.isDesktopApp())
        return this.renderDeskPaymentStation();
      if (n) {
        if (n === f.enum.DONE) {
          window.opener && window.opener.postMessage(JSON.stringify({ message: { action: u.enum.complete } }), "*"), h({ message: { action: u.enum.complete } });
          const r = `${e}?paymentStatus=${n}`;
          return S(r), /* @__PURE__ */ i.createElement(d, { type: E.success, message: "Payment Success" });
        } else if (n === f.enum.CANCELLED) {
          window.opener && window.opener.postMessage(JSON.stringify({ message: { action: u.enum.cancel } }), "*"), h({ message: { action: u.enum.cancel } });
          const r = `${e}?paymentStatus=${n}`;
          return S(r), /* @__PURE__ */ i.createElement(d, { type: E.info, message: "Payment Cancelled" });
        }
      }
      return t != null && t.paymentOrderNo ? /* @__PURE__ */ i.createElement(D, { paymentOrderNo: t.paymentOrderNo, namespace: m, returnUrl: e }) : /* @__PURE__ */ i.createElement("div", { className: "errorContainer" }, /* @__PURE__ */ i.createElement(y, { error: new Error("Invalid request: paymentOrderNo is required") }));
    }
  }, c.IFRAME_ID = "payment-station-iframe", c.IFRAME_SANDBOX_OPTIONS = [
    "allow-forms",
    "allow-modals",
    "allow-orientation-lock",
    "allow-pointer-lock",
    "allow-presentation",
    "allow-same-origin",
    "allow-scripts",
    "allow-popups"
  ].join(" "), c),
  (t, e) => t.order !== e.order
);
export {
  X as PaymentContainer
};
