import { S as format, a1 as v2 } from "./dateFns.js";
import { m as mod, D as DesktopChecker, a as Ctx, M as IFRAME_CHANNEL, P as PaymentStatus, N as v4, Q as IpcChannels, R as AppName, S as PaymentStatusType, W as PaymentAlert, h as AlertType, i as CommonError$1, X as PurchaseHelper, Y as OrderStatus, Z as FeatureFlags, $ as UrlHelper, K as Env, a0 as EcomPath, T as Trans, j as Alert, k as UIEvent, l as bgCommon, a1 as AppType, a2 as ItemType, a3 as Dialog, a4 as DialogBody, a5 as DialogFooter, f as Button, a6 as ButtonType, a7 as ButtonStyle, F as FeUtils, t, L as Loading } from "./index.js";
import React__default from "react";
import { H as HelmetExport } from "./Helmet.js";
import { Redirect, Prompt } from "react-router-dom";
import { P as PaymentStatusNeedMoreTimeProcessedDialog, O as OrderHelper, a as OrderExpiredDialog, b as OrderCancelledDialog, c as PaymentStatusSuccessDialog, d as PaymentStatusProcessedCountDownDialog, e as PaymentStatusFailedDialog } from "./PaymentStatusDialog.js";
import { O as OrderLogic } from "./OrderLogic.js";
import { C as CommonError } from "./CommonError.js";
import { w as withPropsGuard } from "./WithPropsGuard.js";
import { P as PAYMENT_STATION_ACTION_COMPLETE, s as sendMessageToParentWindow, r as redirectToUrlIfExist, a as PaymentStationApp } from "./PaymentStationApp.js";
import { c as classNames } from "./reactSlick.js";
import "./validator.js";
import "./reactPlayer.js";
import "./PendingOrdersAppManager.js";
import "./starBgGradient.js";
import "./CommonError2.js";
import "./Checkbox.js";
var OrderPage$1 = "";
var _a$1;
const AdyenPaymentStatus$1 = mod.enum(["paymentSuccess", "paymentGenericError"]);
const PaymentContainer = withPropsGuard((_a$1 = class extends React__default.Component {
  constructor(props) {
    super(props);
    this.onIframeLoaded = () => {
      const { paymentStationUrl } = this.props;
      if (DesktopChecker.isDesktopApp() && paymentStationUrl) {
        const message = JSON.stringify({
          accessToken: Ctx.getAppState().db.getAccessToken(),
          config: Ctx.getAppState().getConfig(),
          channel: IFRAME_CHANNEL
        });
        const iframeElement = document.getElementById(_a$1.IFRAME_ID).contentWindow;
        if (!iframeElement) {
          return console.log("Message to iframe window ignored");
        }
        iframeElement.postMessage(message, paymentStationUrl);
      }
    };
    this.extractPaymentResult = (maybeUrl) => {
      try {
        if (this.isStringJson(maybeUrl)) {
          const data = JSON.parse(maybeUrl);
          const isSuccessPurchasedWithXsolla = data.action === "complete" || data.paymentStatus;
          if (isSuccessPurchasedWithXsolla) {
            return {
              orderNo: "",
              paymentStatus: PaymentStatus.enum.DONE
            };
          }
          const isPaymentStationEvent = !!data.type && data.type === "paymentStationEvent";
          if (isPaymentStationEvent) {
            const paymentStationStatus = !!data.event.name && data.event.name;
            let paymentResult = null;
            switch (paymentStationStatus) {
              case AdyenPaymentStatus$1.enum.paymentSuccess:
                paymentResult = { orderNo: data.event.orderNo, paymentStatus: PaymentStatus.enum.DONE };
                break;
              case AdyenPaymentStatus$1.enum.paymentGenericError:
                paymentResult = { orderNo: data.event.orderNo, paymentStatus: PaymentStatus.enum.FAILED };
                break;
            }
            return paymentResult;
          }
        }
        return null;
      } catch (error) {
        console.error(error);
        return {
          orderNo: "",
          paymentStatus: PaymentStatus.enum.FAILED
        };
      }
    };
    this.reloadIframe = () => {
      this.setState({ iframeKey: v4() });
    };
    this.listenToPaymentCallback = (event) => {
      const { onPaymentProcessed } = this.props;
      const paymentStationMessage = DesktopChecker.isDesktopApp() && event ? event.data : this.paymentMethodAppManager.state.paymentStationMessage;
      if (!paymentStationMessage)
        return;
      try {
        const paymentResult = this.extractPaymentResult(paymentStationMessage);
        if (paymentResult) {
          switch (paymentResult.paymentStatus) {
            case PaymentStatus.enum.DONE:
              onPaymentProcessed(paymentResult.paymentStatus);
              break;
            case PaymentStatus.enum.FAILED:
              onPaymentProcessed(paymentResult.paymentStatus);
              break;
          }
        }
      } catch (error) {
        console.error(error);
      }
    };
    this.renderDeskPaymentStation = () => {
      const url = this.getPaymentStationUrl();
      if (!url) {
        return /* @__PURE__ */ React__default.createElement("div", {
          className: "errorContainer"
        }, /* @__PURE__ */ React__default.createElement(CommonError, {
          error: new Error()
        }));
      }
      return /* @__PURE__ */ React__default.createElement("iframe", {
        onLoad: this.onIframeLoaded,
        id: _a$1.IFRAME_ID,
        key: this.state.iframeKey,
        className: classNames("paymentStation", this.props.className),
        title: "Pay station",
        src: url,
        sandbox: _a$1.IFRAME_SANDBOX_OPTIONS
      });
    };
    this.state = {
      iframeKey: "0"
    };
    this.paymentMethodAppManager = Ctx.getAppState().paymentMethodManager;
  }
  componentDidMount() {
    this.paymentMethodAppManager.subscribe(this.listenToPaymentCallback);
    if (DesktopChecker.isDesktopApp()) {
      window.addEventListener("message", this.listenToPaymentCallback);
      Device.receive(IpcChannels.OPEN_URL, (url) => {
        const newURL = new URL(url);
        const search = newURL.search;
        const pathname = newURL.pathname.split("/").filter((path) => path !== "").join("/");
        const searchParams = new URLSearchParams(newURL.search);
        const paymentStatus = searchParams.get("paymentStatus");
        if (paymentStatus === PaymentStatus.enum.DONE) {
          this.props.onPaymentProcessed(PaymentStatus.enum.DONE);
        }
        if (paymentStatus === PaymentStatus.enum.FAILED) {
          this.props.onPaymentProcessed(PaymentStatus.enum.FAILED);
        }
        Ctx.getAppState().state.appHistory.replace(`/${pathname}${search}`);
      });
    }
  }
  componentWillUnmount() {
    this.paymentMethodAppManager.unsubscribe(this.listenToPaymentCallback);
    if (DesktopChecker.isDesktopApp()) {
      window.removeEventListener("message", this.listenToPaymentCallback);
      Device.remove(IpcChannels.OPEN_URL);
    }
  }
  getPaymentStationUrl() {
    try {
      const { order, paymentStationUrl, returnUrl } = this.props;
      const url = new URL(paymentStationUrl || order && order.paymentStationUrl || "");
      url.searchParams.append("returnUrl", returnUrl);
      url.searchParams.append("parentAppName", DesktopChecker.isDesktopApp() ? AppName.LAUNCHER : AppName.PP);
      if (order == null ? void 0 : order.paymentOrderNo) {
        url.searchParams.append("paymentOrderNo", order.paymentOrderNo);
      }
      return url.toString();
    } catch (error) {
      return null;
    }
  }
  isStringJson(stringJson) {
    try {
      JSON.parse(stringJson);
    } catch (error) {
      return false;
    }
    return true;
  }
  render() {
    const { order, returnUrl } = this.props;
    const query = new URLSearchParams(window.location.search);
    const paymentStatus = query.get("paymentStatus");
    const namespace = Ctx.getAppState().sdkOptions.namespace;
    if (DesktopChecker.isDesktopApp()) {
      return this.renderDeskPaymentStation();
    }
    if (paymentStatus) {
      if (paymentStatus === PaymentStatusType.enum.DONE) {
        if (window.opener) {
          window.opener.postMessage(JSON.stringify({ message: { action: PAYMENT_STATION_ACTION_COMPLETE } }), "*");
        }
        sendMessageToParentWindow({ message: { action: PAYMENT_STATION_ACTION_COMPLETE } });
        const url = `${returnUrl}?paymentStatus=${paymentStatus}`;
        redirectToUrlIfExist(url);
        return /* @__PURE__ */ React__default.createElement(PaymentAlert, {
          type: AlertType.success,
          message: "Payment Success"
        });
      }
    }
    if (!(order == null ? void 0 : order.paymentOrderNo)) {
      return /* @__PURE__ */ React__default.createElement("div", {
        className: "errorContainer"
      }, /* @__PURE__ */ React__default.createElement(CommonError, {
        error: new Error("Invalid request: paymentOrderNo is required")
      }));
    }
    return /* @__PURE__ */ React__default.createElement(PaymentStationApp, {
      paymentOrderNo: order.paymentOrderNo,
      namespace,
      returnUrl
    });
  }
}, _a$1.IFRAME_ID = "payment-station-iframe", _a$1.IFRAME_SANDBOX_OPTIONS = [
  "allow-forms",
  "allow-modals",
  "allow-orientation-lock",
  "allow-pointer-lock",
  "allow-presentation",
  "allow-same-origin",
  "allow-scripts",
  "allow-popups"
].join(" "), _a$1), (prev, next) => prev.order !== next.order);
var _a;
const AdyenPaymentStatus = mod.enum(["paymentSuccess", "paymentGenericError"]);
const PaymentStation = withPropsGuard((_a = class extends React__default.Component {
  constructor(props) {
    super(props);
    this.paymentSessionCode = String(Math.round(Math.random() * 1e5));
    this.extractPaymentResult = (maybeUrl) => {
      try {
        if (this.isStringJson(maybeUrl)) {
          const data = JSON.parse(maybeUrl);
          const isSuccessPurchasedWithXsolla = data.action === "complete" || data.paymentStatus;
          if (isSuccessPurchasedWithXsolla) {
            return {
              orderNo: "",
              paymentStatus: PaymentStatus.enum.DONE
            };
          }
          const isPaymentStationEvent = !!data.type && data.type === "paymentStationEvent";
          if (isPaymentStationEvent) {
            const paymentStationStatus = !!data.event.name && data.event.name;
            let paymentResult = null;
            switch (paymentStationStatus) {
              case AdyenPaymentStatus.enum.paymentSuccess:
                paymentResult = { orderNo: data.event.orderNo, paymentStatus: PaymentStatus.enum.DONE };
                break;
              case AdyenPaymentStatus.enum.paymentGenericError:
                paymentResult = { orderNo: data.event.orderNo, paymentStatus: PaymentStatus.enum.FAILED };
                break;
            }
            return paymentResult;
          }
        }
        return null;
      } catch (error) {
        console.error(error);
        return {
          orderNo: "",
          paymentStatus: PaymentStatus.enum.FAILED
        };
      }
    };
    this.randomizeNumber = () => {
      return String(Math.floor(Math.random() * 100));
    };
    this.reloadIframe = () => {
      this.setState({ iframeKey: this.randomizeNumber() });
    };
    this.listenToPaymentCallback = (event) => {
      const { onPaymentProcessed } = this.props;
      try {
        const paymentResult = this.extractPaymentResult(event.data);
        if (paymentResult) {
          switch (paymentResult.paymentStatus) {
            case PaymentStatus.enum.DONE:
              onPaymentProcessed(paymentResult.paymentStatus);
              break;
            case PaymentStatus.enum.FAILED:
              onPaymentProcessed(paymentResult.paymentStatus);
              this.reloadIframe();
              break;
          }
        }
      } catch (error) {
        console.error(error);
      }
    };
    this.state = {
      iframeKey: "0"
    };
  }
  getPaymentStationUrl() {
    try {
      const { returnUrl, order, paymentStationUrl } = this.props;
      const url = new URL(paymentStationUrl || order && order.paymentStationUrl || "");
      if (returnUrl) {
        url.searchParams.append("returnUrl", returnUrl);
      }
      return url.toString();
    } catch (error) {
      return null;
    }
  }
  componentDidMount() {
    window.addEventListener("message", this.listenToPaymentCallback);
  }
  componentWillUnmount() {
    window.removeEventListener("message", this.listenToPaymentCallback);
  }
  isStringJson(stringJson) {
    try {
      JSON.parse(stringJson);
    } catch (error) {
      return false;
    }
    return true;
  }
  render() {
    const url = this.getPaymentStationUrl();
    if (!url) {
      return /* @__PURE__ */ React__default.createElement("div", {
        className: "errorContainer"
      }, /* @__PURE__ */ React__default.createElement(CommonError$1, {
        error: new Error()
      }));
    }
    return /* @__PURE__ */ React__default.createElement("iframe", {
      key: this.state.iframeKey,
      className: classNames("paymentStation", this.props.className),
      title: "Pay station",
      src: url,
      sandbox: _a.IFRAME_SANDBOX_OPTIONS
    });
  }
}, _a.IFRAME_SANDBOX_OPTIONS = [
  "allow-forms",
  "allow-modals",
  "allow-orientation-lock",
  "allow-pointer-lock",
  "allow-presentation",
  "allow-same-origin",
  "allow-scripts",
  "allow-popups"
].join(" "), _a), (prev, next) => prev.order !== next.order);
const PROCESSED_DIALOG_COUNTDOWN_IN_SECOND = 5;
const DEFAULT_RETRY_TIMEOUT = 1e3;
class OrderPage extends React__default.Component {
  constructor(props) {
    var _a2;
    super(props);
    this.randomString = String(Math.round(Math.random() * 1e5));
    this.getFormatedPrice = (price, currency) => `${currency.currencySymbol} ${PurchaseHelper.calculateIntegerPrice(price, currency)}`;
    this.calculateSubtotalPrice = (price, quantity, currency) => {
      const totalPrice = price * quantity;
      return this.getFormatedPrice(totalPrice, currency);
    };
    this.calculateTotalDiscount = (price, discountedPrice, currency) => {
      const totalDiscount = price - discountedPrice;
      return `- ${this.getFormatedPrice(totalDiscount, currency)}`;
    };
    this.onPaymentSuccess = async () => {
      const { orderNo } = this.props;
      await this.logic.fetchOrder(orderNo);
      await Ctx.getAppState().refreshWallet();
      const { order } = this.logic.state;
      this.setState({ paymentStatus: PaymentStatus.enum.DONE });
      if (!order)
        return;
      switch (order.status) {
        case OrderStatus.enum.INIT:
          this.retryCheckOrderStatus();
          this.setState({
            paymentStatusProcessedCountDownDialogIsOpen: true
          });
          break;
        case OrderStatus.enum.CHARGED:
        case OrderStatus.enum.FULFILLED:
          this.setState({ paymentStatusSuccessIsOpen: true });
          break;
      }
    };
    this.retryCheckOrderStatus = async (retry = PROCESSED_DIALOG_COUNTDOWN_IN_SECOND, timeout = DEFAULT_RETRY_TIMEOUT) => {
      const { orderNo } = this.props;
      await this.logic.fetchOrder(orderNo);
      const { order } = this.logic.state;
      if (!order)
        return;
      if (order.status === OrderStatus.enum.FULFILLED) {
        window.removeEventListener("beforeunload", this.onReloadPageWarningWhileStillInCountdown, false);
        this.setState({
          paymentStatusProcessedCountDownDialogIsOpen: false,
          paymentStatusSuccessIsOpen: true
        });
      }
      if (order.status === OrderStatus.enum.INIT && retry > 0) {
        setTimeout(() => {
          this.retryCheckOrderStatus(retry - 1, timeout);
        }, timeout);
      }
      if (retry === 0) {
        this.setState({
          paymentStatusProcessedCountDownDialogIsOpen: false,
          paymentStatusNeedMoreTimeProcessedDialogIsOpen: true
        });
      }
    };
    this.onPaymentStatusNeedMoreTimeProcessedDialogClose = () => {
      this.setState({
        paymentStatusNeedMoreTimeProcessedDialogIsOpen: false
      });
    };
    this.renderPaymentStatusNeedMoreTimeProcessedDialog = () => {
      return /* @__PURE__ */ React__default.createElement(PaymentStatusNeedMoreTimeProcessedDialog, {
        onClose: this.redirectToItemPage
      });
    };
    this.renderPaymentStation = (order) => {
      const isOdinPaymentEnabled = Ctx.hasFeature(FeatureFlags.isOdinPaymentEnabled);
      return isOdinPaymentEnabled ? /* @__PURE__ */ React__default.createElement(PaymentContainer, {
        order,
        onPaymentProcessed: (paymentStatus) => {
          switch (paymentStatus) {
            case PaymentStatus.enum.DONE:
              OrderHelper.handleOrderFulfillmentImplication(order);
              this.onPaymentSuccess();
              break;
            case PaymentStatus.enum.FAILED:
              this.setState({ paymentStatus });
              break;
          }
        },
        paymentStationUrl: DesktopChecker.isDesktopApp() ? UrlHelper.combineURLPaths(Env.IS_DEV_MODE ? "http://localhost:3030" : Env.BASE_URL, Env.PLAYER_PORTAL_BASE_URL, "payment/index.html") : void 0,
        returnUrl: DesktopChecker.isDesktopApp() ? `${Env.REDIRECT_URL}/${Ctx.getAppState().state.appHistory.location.pathname}` : UrlHelper.combineURLPaths(window.location.origin, Env.PLAYER_PORTAL_BASE_URL, EcomPath.PaymentSuccessCallback.makePath())
      }) : /* @__PURE__ */ React__default.createElement(PaymentStation, {
        order,
        onPaymentProcessed: (paymentStatus) => {
          switch (paymentStatus) {
            case PaymentStatus.enum.DONE:
              OrderHelper.handleOrderFulfillmentImplication(order);
              this.onPaymentSuccess();
              break;
            case PaymentStatus.enum.FAILED:
              this.setState({ paymentStatus });
              break;
          }
        },
        returnUrl: UrlHelper.combineURLPaths(window.location.origin, Env.PLAYER_PORTAL_BASE_URL, EcomPath.PaymentSuccessCallback.makePath())
      });
    };
    this.renderOrderContent = (order, itemSnapshot) => {
      if (!order.expireTime)
        return;
      const { paymentStatus } = this.state;
      const expirationTime = format(v2.legacyParse(order.expireTime), "D MMM YYYY hh:mm a");
      return /* @__PURE__ */ React__default.createElement("div", {
        className: "orderContent"
      }, /* @__PURE__ */ React__default.createElement("div", {
        className: "orderCard"
      }, /* @__PURE__ */ React__default.createElement("div", {
        className: "orderHeader"
      }, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "OrderPage.orderContent.title"
      }, "Payment")), /* @__PURE__ */ React__default.createElement("div", {
        className: "orderExpire"
      }, itemSnapshot.regionDataItem && /* @__PURE__ */ React__default.createElement(Alert, {
        type: AlertType.info
      }, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "OrderPage.orderExpire.title"
      }, "This order will expire at"), "\xA0", expirationTime)), order && order.status === OrderStatus.enum.INIT && paymentStatus !== PaymentStatus.enum.DONE && /* @__PURE__ */ React__default.createElement("section", {
        className: "paymentSection",
        id: "paymentSection"
      }, this.renderPaymentStation(order), /* @__PURE__ */ React__default.createElement("div", {
        className: "btnContainer"
      }, /* @__PURE__ */ React__default.createElement("button", {
        disabled: order.status !== OrderStatus.enum.INIT,
        onClick: () => this.openCancellationDialog(),
        className: "btn btn-ghost"
      }, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "OrderPage.cancelOrder"
      }, "Cancel"))))), /* @__PURE__ */ React__default.createElement("button", {
        disabled: order.status !== OrderStatus.enum.INIT,
        onClick: () => this.openCancellationDialog(),
        className: "btn btnCancel"
      }, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "OrderPage.cancelOrder"
      }, "Cancel")));
    };
    this.redirectToItemPage = () => {
      this.setState({ shouldRedirect: true });
    };
    this.restartPayment = () => {
      this.setState({ paymentStatus: null, paymentStatusSuccessIsOpen: false });
    };
    const userId = ((_a2 = Ctx.getAppState().getUser()) == null ? void 0 : _a2.userId) || "";
    this.logic = new OrderLogic({
      orderNo: props.orderNo,
      userId
    });
    this.logic.subscribe(() => this.setState({}));
    this.state = {
      paymentStatus: null,
      orderInfo: null,
      shouldRedirect: false,
      cancellationDialogIsOpen: false,
      cancellationNoticeIsOpen: false,
      paymentStatusSuccessIsOpen: false,
      paymentStatusProcessedCountDownDialogIsOpen: false,
      paymentStatusNeedMoreTimeProcessedDialogIsOpen: false
    };
  }
  componentDidMount() {
    window.addEventListener("beforeunload", this.onReloadPageWarningWhileStillInCountdown, false);
    this.logic.init();
    UIEvent.updateBackground(`url(${bgCommon})`);
  }
  onReloadPageWarningWhileStillInCountdown(e) {
    e.preventDefault();
  }
  componentWillUnmount() {
    window.removeEventListener("beforeunload", this.onReloadPageWarningWhileStillInCountdown, false);
  }
  renderRedirection() {
    if (this.props.redirectPath) {
      return /* @__PURE__ */ React__default.createElement(Redirect, {
        to: this.props.redirectPath
      });
    }
    const { order } = this.logic.state;
    if (order && order.itemSnapshot) {
      const { itemType, itemId, appType } = order.itemSnapshot;
      if (appType && itemId) {
        switch (appType) {
          case AppType.enum.DLC:
            return /* @__PURE__ */ React__default.createElement(Redirect, {
              to: EcomPath.DlcItem.makePath({ itemId })
            });
        }
      }
      if (itemType && itemId) {
        switch (itemType) {
          case ItemType.enum.APP:
            return /* @__PURE__ */ React__default.createElement(Redirect, {
              to: EcomPath.GameItem.makePath({ itemId })
            });
          case ItemType.enum.BUNDLE:
            return /* @__PURE__ */ React__default.createElement(Redirect, {
              to: EcomPath.BundleItem.makePath({ itemId })
            });
          case ItemType.enum.CODE:
            return /* @__PURE__ */ React__default.createElement(Redirect, {
              to: EcomPath.CodeItem.makePath({ itemId })
            });
          case ItemType.enum.INGAMEITEM:
            return /* @__PURE__ */ React__default.createElement(Redirect, {
              to: EcomPath.InGameItem.makePath({ itemId })
            });
          case ItemType.enum.COINS:
            return /* @__PURE__ */ React__default.createElement(Redirect, {
              to: EcomPath.Recharge.withSearchParams({ recharge: "true" })
            });
          default:
            return /* @__PURE__ */ React__default.createElement(Redirect, {
              to: `/`
            });
        }
      }
    }
    return null;
  }
  openCancellationNotice() {
    this.setState({ cancellationNoticeIsOpen: true });
  }
  openCancellationDialog() {
    this.setState({ cancellationDialogIsOpen: true });
  }
  closeCancellationDialog() {
    this.setState({ cancellationDialogIsOpen: false });
  }
  renderCancellationDialog() {
    const {
      state: { isCancelling, cancellationError }
    } = this.logic;
    return /* @__PURE__ */ React__default.createElement(Dialog, {
      className: "orderDialog",
      title: /* @__PURE__ */ React__default.createElement("h2", null, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "OrderPage.cancellationDialog.title"
      }, "Confirm Cancellation")),
      isOpen: true
    }, /* @__PURE__ */ React__default.createElement(DialogBody, null, /* @__PURE__ */ React__default.createElement("p", null, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "OrderPage.cancellationDialog.message"
    }, "You're just one step away from completing payment, are you sure you want to cancel this order?")), cancellationError && /* @__PURE__ */ React__default.createElement("div", {
      className: "errorContainer"
    }, /* @__PURE__ */ React__default.createElement(CommonError$1, {
      error: cancellationError
    }))), /* @__PURE__ */ React__default.createElement(DialogFooter, {
      className: "orderCancellationDialogFooter"
    }, /* @__PURE__ */ React__default.createElement("div", {
      className: "btnContainer"
    }, /* @__PURE__ */ React__default.createElement(Button, {
      disabled: isCancelling,
      onClick: () => this.closeCancellationDialog(),
      className: "btn btn-ghost uppercase",
      buttonType: ButtonType.TEXT,
      buttonStyle: ButtonStyle.NONE
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "OrderPage.cancellationDialog.backButton"
    }, "Back")), /* @__PURE__ */ React__default.createElement(Button, {
      loadingIndicator: "SPINNER",
      className: "btn-primary uppercase",
      isLoading: isCancelling,
      onClick: () => this.cancelOrder()
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "OrderPage.cancellationDialog.cancelButton"
    }, "Cancel Order")))));
  }
  renderExpiryDialog() {
    const { order, orderIsExpired } = this.logic.state;
    if (!order)
      return null;
    if (order.status !== OrderStatus.enum.CLOSED && !orderIsExpired)
      return;
    return /* @__PURE__ */ React__default.createElement(OrderExpiredDialog, {
      className: "orderDialog",
      onCloseDialog: () => this.redirectToItemPage()
    });
  }
  renderCancellationNotice() {
    return /* @__PURE__ */ React__default.createElement(OrderCancelledDialog, {
      className: "orderDialog",
      onCloseDialog: () => this.redirectToItemPage()
    });
  }
  async cancelOrder() {
    await this.logic.cancelAllOrders();
    const { cancellationError } = this.logic.state;
    if (cancellationError)
      return;
    await this.setState({ cancellationNoticeIsOpen: true, cancellationDialogIsOpen: false });
  }
  render() {
    const {
      shouldRedirect,
      paymentStatus,
      paymentStatusSuccessIsOpen,
      paymentStatusProcessedCountDownDialogIsOpen,
      paymentStatusNeedMoreTimeProcessedDialogIsOpen
    } = this.state;
    const { isFetching, error, order } = this.logic.state;
    const isPaymentStatusDialogOpen = paymentStatusSuccessIsOpen || paymentStatusProcessedCountDownDialogIsOpen || paymentStatusNeedMoreTimeProcessedDialogIsOpen;
    if (order && shouldRedirect) {
      return this.renderRedirection();
    }
    if (order && order.status === OrderStatus.enum.FULFILLED) {
      window.removeEventListener("beforeunload", this.onReloadPageWarningWhileStillInCountdown, false);
      return /* @__PURE__ */ React__default.createElement(PaymentStatusSuccessDialog, {
        className: "orderDialog",
        orderInfo: order,
        onCloseDialog: () => this.redirectToItemPage()
      });
    }
    return /* @__PURE__ */ React__default.createElement("main", {
      className: "orderDetailPage"
    }, /* @__PURE__ */ React__default.createElement(HelmetExport, null, /* @__PURE__ */ React__default.createElement("title", null, FeUtils.makeTitleWithAppName(t("Order.title")))), order && order.status === OrderStatus.enum.INIT && /* @__PURE__ */ React__default.createElement(Prompt, {
      message: () => /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "OrderPage.navigationPrompt"
      }, "You have not completed this transaction. You will need to finish or cancel this transaction before you can place another order. Are you sure you want to navigate away?")
    }), paymentStatusNeedMoreTimeProcessedDialogIsOpen && this.renderPaymentStatusNeedMoreTimeProcessedDialog(), paymentStatusProcessedCountDownDialogIsOpen && /* @__PURE__ */ React__default.createElement(PaymentStatusProcessedCountDownDialog, null), paymentStatusSuccessIsOpen && order && /* @__PURE__ */ React__default.createElement(PaymentStatusSuccessDialog, {
      className: "orderDialog",
      orderInfo: order,
      onCloseDialog: () => this.redirectToItemPage()
    }), paymentStatus && paymentStatus === PaymentStatus.enum.FAILED && /* @__PURE__ */ React__default.createElement(PaymentStatusFailedDialog, {
      className: "orderDialog",
      onCloseDialog: () => this.restartPayment()
    }), this.renderExpiryDialog(), this.state.cancellationNoticeIsOpen && this.renderCancellationNotice(), this.state.cancellationDialogIsOpen && this.renderCancellationDialog(), isFetching && /* @__PURE__ */ React__default.createElement(Loading, null), !isFetching && /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, error && /* @__PURE__ */ React__default.createElement("div", {
      className: "errorContainer"
    }, /* @__PURE__ */ React__default.createElement(CommonError$1, {
      error
    })), order && order.itemSnapshot && !isPaymentStatusDialogOpen && this.renderOrderContent(order, order.itemSnapshot)));
  }
}
export { OrderPage as default };
