import { Alert as K } from "./accelbyte-widgets123.mjs";
import { WarningIcon as z } from "./accelbyte-widgets402.mjs";
import { Loading as X } from "./accelbyte-widgets136.mjs";
import { Spinner as J, SpinnerStyle as Z } from "./accelbyte-widgets154.mjs";
import $ from "./accelbyte-widgets210.mjs";
import { Ctx as _ } from "./accelbyte-widgets33.mjs";
import { Env as ee } from "./accelbyte-widgets108.mjs";
import { AlertType as G } from "./accelbyte-widgets128.mjs";
import { ItemType as k, EntitlementType as te } from "./accelbyte-widgets185.mjs";
import { AccPath as re } from "./accelbyte-widgets34.mjs";
import { EcomPath as Y } from "./accelbyte-widgets59.mjs";
import { LoginPath as V } from "./accelbyte-widgets35.mjs";
import { ErrorHelper as Q } from "./accelbyte-widgets120.mjs";
import { RegionDataItemHelper as f } from "./accelbyte-widgets388.mjs";
import { UrlUtils as ne } from "./accelbyte-widgets90.mjs";
import { OrderAppManager as ie } from "./accelbyte-widgets403.mjs";
import { isValid as ae, isBefore as se } from "date-fns";
import { DesktopChecker as B, UrlHelper as oe } from "@accelbyte/sdk";
import e from "react";
import le from "classnames";
import { Trans as s } from "react-i18next";
import { Link as q } from "react-router-dom";
import { z as ce } from "zod";
import { OrderHelper as H } from "./accelbyte-widgets298.mjs";
import { PaymentStatusSuccessDialog as me } from "./accelbyte-widgets299.mjs";
import { PurchaseDialog as ue } from "./accelbyte-widgets404.mjs";
import { ClaimFailedDialog as pe } from "./accelbyte-widgets405.mjs";
import { ClaimSuccessDialog as he } from "./accelbyte-widgets406.mjs";
import { DownloadLauncherDialog as de } from "./accelbyte-widgets407.mjs";
import { OpenLibraryLauncherButton as ge } from "./accelbyte-widgets219.mjs";
import { PurchaseRequirementUnmatchListDialog as Ee } from "./accelbyte-widgets408.mjs";
import "./accelbyte-widgets409.mjs";
import { PlayButton as Ce } from "./accelbyte-widgets410.mjs";
import { PriceList as fe } from "./accelbyte-widgets411.mjs";
import { PurchaseAccessibleItemDialog as Pe } from "./accelbyte-widgets412.mjs";
import { PurchaseButton as ye } from "./accelbyte-widgets413.mjs";
import { UserBannedAlert as Ie } from "./accelbyte-widgets414.mjs";
import { mockUser as De, mockPaymentConstraint as Ae } from "./accelbyte-widgets209.mjs";
import { OrderStatus as W } from "@accelbyte/sdk-platform";
import { IamHelper as Se } from "@accelbyte/sdk-iam";
import { FeatureFlags as Le } from "./accelbyte-widgets57.mjs";
import { Tabs as be, TabStyles as j } from "./accelbyte-widgets174.mjs";
import { InfoIcon as Oe } from "./accelbyte-widgets330.mjs";
const a = ce.enum([
  "PURCHASE",
  "DOWNLOAD_LAUNCHER",
  "CLAIM_SUCCESS",
  "CLAIM_FAILED",
  "PAYMENT_SUCCESS",
  "PURCHASE_ACCESSIBLE_ITEM",
  "PURCHASING_REQUIREMENT_ERROR"
]), F = 3, ft = $(
  class extends e.Component {
    constructor(n) {
      var h, o, P;
      super(n), this.handleCreatedOrder = (t) => {
        const { item: r } = this.props, l = f.isFree(f.getCurrentRegionData(r, t.currency.currencyCode));
        if (t.status === W.enum.INIT) {
          const m = this.appState.state.appHistory;
          m.push(Y.OrderDetail.makePath({ orderNo: t.orderNo }, { referrer: m.location.pathname }));
        }
        t.status === W.enum.FULFILLED && (r.flexible || this.logic.fetchData(), l ? this.setState({ openDialog: a.enum.CLAIM_SUCCESS }) : this.setState({ openDialog: a.enum.PAYMENT_SUCCESS }));
      }, this.handlePurchaseError = (t) => {
        const { item: r } = this.props;
        f.isFree(f.getCurrentRegionData(r, t == null ? void 0 : t.currencyCode)) && this.setState({ openDialog: a.enum.CLAIM_FAILED });
      }, this.handlePurchase = (t) => {
        var m;
        if (!!!((m = this.appState.getUser()) == null ? void 0 : m.userId)) {
          this.redirectToLoginPage();
          return;
        }
        if (!B.isDesktopApp() && this.isItemAccessible()) {
          this.setState({
            openDialog: a.enum.PURCHASE_ACCESSIBLE_ITEM,
            selectedRegionData: t,
            purchaseQuantity: 1
          });
          return;
        }
        this.setState({
          openDialog: a.enum.PURCHASE,
          selectedRegionData: t,
          purchaseQuantity: 1
        });
      }, this.renderLauncherGoToLibraryButton = () => {
        const { item: t, renderLauncherGoToLibraryButton: r } = this.props;
        return r ? r() : /* @__PURE__ */ e.createElement(ge, { item: t });
      }, this.claimFreeItem = async () => {
        var C;
        const { item: r } = this.props, { activatedRegionData: l } = this.logic.state;
        if (!!!(((C = this.appState.getUser()) == null ? void 0 : C.userId) || null)) {
          this.redirectToLoginPage();
          return;
        }
        const g = f.getFirstFreeRegionDatum(
          f.getCurrentRegionData(r, l == null ? void 0 : l.currencyCode)
        );
        if (!g)
          return;
        await this.logic.purchase({
          regionData: g,
          quantity: 1,
          returnUrl: B.isDesktopApp() ? H.AVOID_REDIRECT_TO_FILE_PROTOCOL : oe.combineURLPaths(window.location.origin, ee.PLAYER_PORTAL_BASE_URL)
        });
        const { createdOrder: d } = this.logic.state;
        d && (this.handleCreatedOrder(d), H.handleOrderCreationImplication(d), d.status === W.enum.FULFILLED && H.handleOrderFulfillmentImplication(d));
      }, this.renderClaimButton = (t) => {
        const { isPurchasing: r } = this.logic.state;
        return /* @__PURE__ */ e.createElement("button", { className: "btn btn-primary", onClick: () => this.claimFreeItem(), disabled: t }, r && /* @__PURE__ */ e.createElement(J, { className: Z.inline }), !r && /* @__PURE__ */ e.createElement(s, { i18nKey: "CatalogPurchaseWidget.button.claim" }, "CLAIM NOW"));
      }, this.renderPurchaseButtonPreview = () => /* @__PURE__ */ e.createElement("button", { className: "btn btn-primary" }, "PURCHASE"), this.renderOwnedButton = () => /* @__PURE__ */ e.createElement("button", { className: "btn btn-primary", disabled: !0 }, /* @__PURE__ */ e.createElement(s, { i18nKey: "CatalogPurchaseWidget.button.owned" }, "OWNED")), this.renderMiniLauncherButton = () => {
        const { itemPublishingContent: t } = this.props;
        return t ? /* @__PURE__ */ e.createElement("a", { className: "btn big btn-primary text-uppercase", href: t.miniLauncherUrl }, /* @__PURE__ */ e.createElement(s, { i18nKey: "CatalogPurchaseWidget.button.play" }, "PLAY")) : null;
      }, this.itemIsOwned = () => {
        const { itemOwnership: t } = this.logic.state;
        return !!(t && t.owned);
      }, this.itemRequireBaseApp = () => {
        const { item: t } = this.props;
        return t.itemType === k.enum.INGAMEITEM;
      }, this.onSelectRegionData = (t) => {
        this.logic.setState({ activatedRegionData: t });
      }, this.renderWidgetButton = (t) => {
        var x;
        const { item: r, itemPublishingContent: l, itemsInBundle: m, purchaseLogic: E, isPreviewMode: g } = this.props, { isPurchasing: d, availableItemInfo: C, baseAppOwnership: D, activatedRegionData: A } = this.logic.state, u = (x = this.appState.getUser()) == null ? void 0 : x.userId, { pendingOrders: U } = this.logic.state, S = f.isFree(f.getCurrentRegionData(r, A == null ? void 0 : A.currencyCode)), T = !!U && U.length > 0, O = !!(C && C.userPurchaseLimit === 0), R = !(E && E.checkCanUserPurchase()), w = r.itemType === k.enum.APP;
        m && m.find((N) => N.itemType === k.enum.INGAMEITEM);
        const y = this.itemRequireBaseApp(), M = D == null ? void 0 : D.owned, L = r.itemType === k.enum.INGAMEITEM && r.entitlementType === te.enum.DURABLE, v = !!u, I = v && y && !M || !r.purchasable || O;
        switch (!0) {
          case g:
            return this.renderPurchaseButtonPreview();
          case (w && this.itemIsOwned() && B.isDesktopApp()):
            return this.renderLauncherGoToLibraryButton();
          case (w && this.itemIsOwned() && !B.isDesktopApp()):
            return l && ne.isValidUrl(l.miniLauncherUrl) ? this.renderMiniLauncherButton() : /* @__PURE__ */ e.createElement(Ce, { onClickPlay: () => this.setState({ openDialog: a.enum.DOWNLOAD_LAUNCHER }) });
          case (this.itemIsOwned() && (O || L || r.flexible)):
            return this.renderOwnedButton();
          case (!this.itemIsOwned() && r.regionData && S):
            return this.renderClaimButton(I);
          case t.length === 0:
            return this.renderPaymentUnavailable();
          default:
            return /* @__PURE__ */ e.createElement(
              ye,
              {
                className: "purchaseButton",
                isPurchasing: d,
                disabled: !r.purchasable || v && (d || this.isUserBanned() || T || O || R || y && !M || !r.purchasable),
                onPurchase: (N) => this.handlePurchase(N),
                paymentOptions: t.map((N) => N.paymentOption)
              }
            );
        }
      }, this.renderPaymentUnavailable = () => {
        const { additionalAppInfo: t } = this.props;
        if (t) {
          const r = new Date(t.releaseDate || "");
          if (ae(r) && se(new Date(), r))
            return /* @__PURE__ */ e.createElement("div", { className: "paymentUnavailable catalogPurchaseWidgetReleaseDate" }, /* @__PURE__ */ e.createElement(s, { i18nKey: "CatalogPurchaseWidget.comingSoonDate" }, "Release on ", { releaseDate: r }));
        }
        return /* @__PURE__ */ e.createElement("div", { className: "paymentUnavailable" }, /* @__PURE__ */ e.createElement(s, { i18nKey: "CatalogPurchaseWidget.cantPurchasedYet" }, "Sorry, this item cannot be purchased yet. Please return to the store to continue shopping."));
      }, this.renderPurchasingRequirementNotMetTip = () => {
        var C, D, A;
        const { unmatchedPurchaseRequirementItems: t, purchaseConditionValidation: r } = this.logic.state;
        if (!(t != null && t.length))
          return;
        const { item: l } = this.props;
        let m = (t == null ? void 0 : t.map((u) => u.itemId)) || [];
        const E = [], g = [];
        if (r) {
          const u = ((C = r[0]) == null ? void 0 : C.validateDetails) || [], U = u.length;
          for (let S = 0; S < U && m.length !== 0; S++) {
            const T = ((D = u[S]) == null ? void 0 : D.predicateValidateResults) || [], O = T.length, R = (((A = l == null ? void 0 : l.purchaseCondition) == null ? void 0 : A.conditionGroups) || [])[S], w = (R == null ? void 0 : R.predicates) || [];
            for (let y = 0; y < O; y++) {
              const { validated: M, unmatched: L } = T[y], { comparison: v } = w[y];
              if (!M && L)
                switch (m = m.filter((I) => L.includes(I)), v) {
                  case "includes":
                    E.push(
                      ...t.filter((I) => L.includes(I.itemId))
                    );
                    break;
                  case "excludes":
                    g.push(
                      ...t.filter((I) => L.includes(I.itemId))
                    );
                    break;
                }
            }
          }
        }
        const d = E.length > F || g.length > F;
        return /* @__PURE__ */ e.createElement("div", { className: "purchasingRequirementNotMetTip" }, /* @__PURE__ */ e.createElement(z, { className: "icon-warning" }), /* @__PURE__ */ e.createElement("div", null, /* @__PURE__ */ e.createElement(s, { i18nKey: "CommonTip.userNotMeetItemPurchaseCondition" }, "To purchase this item, you must satisfy the following condition(s):"), !!E.length && /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement("p", null, /* @__PURE__ */ e.createElement(s, { i18nKey: "CommonTip.userNotMeetIncludeItemPurchaseCondition" }, "Must first purchase below item(s):")), /* @__PURE__ */ e.createElement("ul", { className: "item-list" }, E.slice(0, F).map(({ title: u }) => /* @__PURE__ */ e.createElement("li", { key: u }, u)))), !!g.length && /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement("p", null, /* @__PURE__ */ e.createElement(s, { i18nKey: "CommonTip.userNotMeetExcludeItemPurchaseCondition" }, "Cannot own below item(s):")), /* @__PURE__ */ e.createElement("ul", { className: "item-list" }, g.slice(0, F).map(({ title: u }) => /* @__PURE__ */ e.createElement("li", { key: u }, u)))), d && /* @__PURE__ */ e.createElement(
          "span",
          {
            className: "button-see-more",
            onClick: () => {
              this.setState({ openDialog: a.enum.PURCHASING_REQUIREMENT_ERROR });
            }
          },
          /* @__PURE__ */ e.createElement(s, { i18nKey: "common.seeMore" }, "See More")
        )));
      }, this.closeDialog = () => {
        const { item: t, bundleLogic: r } = this.props, { openDialog: l } = this.state;
        l && this.setState({ openDialog: null }, () => {
          t.flexible && (r == null || r.init());
        });
      };
      const { item: i, isPreviewMode: c } = n;
      this.state = {
        selectedRegionData: null,
        purchaseQuantity: 1,
        openDialog: null
      }, this.appState = _.getAppState();
      const p = ((h = this.appState.getUser()) == null ? void 0 : h.userId) || null;
      if (this.logic = this.props.purchaseLogic || new ie(_.getAppState().getSdk(), {
        item: i,
        userId: p
      }), !c && i.flexible) {
        const { purchaseConstraint: t } = this.logic.state;
        this.logic.setState({ activatedRegionData: ((P = (o = t == null ? void 0 : t.paymentConstraints) == null ? void 0 : o[0]) == null ? void 0 : P.paymentOption.regionData) || null });
      }
      this.logic.subscribe(() => this.setState({}));
    }
    componentDidMount() {
      if (this.props.isCheckoutPreview)
        return this.setState({
          openDialog: a.enum.PURCHASE
        });
      this.props.isPreviewMode || this.logic.init();
    }
    componentDidUpdate(n) {
      n.isCheckoutPreview !== this.props.isCheckoutPreview && this.setState({
        openDialog: a.enum.PURCHASE
      });
    }
    isUserBanned() {
      const n = _.getAppState().getUser();
      return Se.isUserBanned(n);
    }
    redirectToLoginPage() {
      const {
        state: { appHistory: n }
      } = this.appState, {
        location: { pathname: i }
      } = n;
      n.push(
        V.Login.withSearchParams({
          [V.LoginURLGeneratorParamKeys.RETURN_PATH_PARAMS_KEY]: i
        })
      );
    }
    isItemAccessible() {
      const { item: n } = this.props, i = _.getAppState().featureFlagsManager.hasFeature(Le.isSubscriptionsVisible);
      return !!n.features && i;
    }
    renderPurchaseAccessibleItemDialog() {
      return /* @__PURE__ */ e.createElement(
        Pe,
        {
          item: this.props.item,
          onClose: this.closeDialog,
          onBuy: () => this.setState({
            openDialog: a.enum.PURCHASE
          })
        }
      );
    }
    renderPurchaseDialog() {
      var h;
      const { item: n, isCheckoutPreview: i } = this.props, c = i ? De.userId : (h = this.appState.getUser()) == null ? void 0 : h.userId, { openDialog: p } = this.state;
      if (!(!c || p !== a.enum.PURCHASE))
        return /* @__PURE__ */ e.createElement(
          ue,
          {
            title: /* @__PURE__ */ e.createElement(s, { i18nKey: "CatalogPurchaseWidget.dialog.purchase.title" }, "Checkout"),
            item: n,
            onClose: i ? () => null : this.closeDialog,
            preSelectedRegionData: this.state.selectedRegionData || void 0,
            purchaseLogic: this.logic,
            onPurchase: this.handleCreatedOrder,
            onPurchaseError: this.handlePurchaseError,
            isPreviewMode: i
          }
        );
    }
    renderPendingOrderAlert() {
      const { paymentInfo: n, pendingOrders: i } = this.logic.state;
      if (!(!i || i.length === 0))
        return n && n.charging ? /* @__PURE__ */ e.createElement("div", { className: "pendingOrderAlertContainer" }, /* @__PURE__ */ e.createElement(K, { className: "pendingOrderAlert", type: G.info }, /* @__PURE__ */ e.createElement("div", null, /* @__PURE__ */ e.createElement(s, { i18nKey: "CatalogPurchaseWidget.pendingPaymentExist.message" }, "You already have a pending order for this item.")), /* @__PURE__ */ e.createElement("div", null, /* @__PURE__ */ e.createElement(
          q,
          {
            to: re.OrderHistoryDetail.makePath({
              orderNo: i[0].orderNo
            })
          },
          /* @__PURE__ */ e.createElement(s, { i18nKey: "CatalogPurchase.pendingPaymentExist.viewOrderDetail" }, "View Order Detail")
        )))) : /* @__PURE__ */ e.createElement("div", { className: "pendingOrderAlertContainer" }, /* @__PURE__ */ e.createElement(K, { className: "pendingOrderAlert", type: G.info }, /* @__PURE__ */ e.createElement("div", null, /* @__PURE__ */ e.createElement(s, { i18nKey: "CatalogPurchaseWidget.pendingOrdersExist.message" }, "You already have another pending order that contains this item. Please complete that order before making another purchase.")), /* @__PURE__ */ e.createElement("div", null, /* @__PURE__ */ e.createElement(
          q,
          {
            to: Y.OrderDetail.makePath(
              {
                orderNo: i[0].orderNo
              },
              {
                referrer: this.appState.state.appHistory.location.pathname
              }
            )
          },
          /* @__PURE__ */ e.createElement(s, { i18nKey: "CatalogPurchaseW.pendingOrdersExist.linkToOrder" }, "Continue to Checkout")
        ))));
    }
    renderPurchaseWidgetContent() {
      const { isPreviewMode: n } = this.props, { purchaseConstraint: i, activatedRegionData: c } = this.logic.state, { item: p } = this.props, h = n ? Ae : i;
      if (!h)
        return;
      const { paymentConstraints: o } = h, P = o.filter((r) => r.paymentOption.regionData.currencyCode === (c == null ? void 0 : c.currencyCode) || !p.flexible).map((r) => r.paymentOption), t = this.itemIsOwned();
      return /* @__PURE__ */ e.createElement(e.Fragment, null, p.flexible && o.length > 1 && /* @__PURE__ */ e.createElement(be, null, o.map((r) => /* @__PURE__ */ e.createElement(
        "span",
        {
          className: le(j.tab, {
            [j.active]: r.paymentOption.regionData.currencyCode === (c == null ? void 0 : c.currencyCode)
          }),
          key: r.paymentOption.regionData.currencyCode,
          onClick: () => this.onSelectRegionData(r.paymentOption.regionData)
        },
        r.paymentOption.regionData.currencyCode
      ))), /* @__PURE__ */ e.createElement("div", { className: "priceListContainer" }, t || p.purchasable ? o && o.length > 0 && /* @__PURE__ */ e.createElement(fe, { className: "priceList", paymentOptions: P }) : /* @__PURE__ */ e.createElement("div", { className: "unpurchasable-info" }, /* @__PURE__ */ e.createElement(s, { i18nKey: "CatalogPurchaseWidget.unpurchasable.info" }, "Sorry, this product is not purchasable.")), this.renderWidgetButton(o)), p.flexible && /* @__PURE__ */ e.createElement("p", { className: "flexible-tips" }, /* @__PURE__ */ e.createElement(Oe, { fillColor: "none", stroke: "#FFFFFF" }), /* @__PURE__ */ e.createElement(s, { i18nKey: "CatalogPurchaseWidget.purchaseTips" }, "You will only pay for and receive items you do not yet own.")), this.renderPurchasingRequirementNotMetTip());
    }
    render() {
      const { itemPublishingContent: n } = this.props, { isFetching: i, fetchError: c, createdOrder: p, unmatchedPurchaseRequirementItems: h } = this.logic.state, { openDialog: o } = this.state, { item: P } = this.props, t = location.pathname.includes("/player-portal/checkout");
      return /* @__PURE__ */ e.createElement("div", { className: "catalogPurchaseWidget" }, (o === a.enum.PURCHASE || t) && this.renderPurchaseDialog(), o === a.enum.PURCHASE_ACCESSIBLE_ITEM && this.renderPurchaseAccessibleItemDialog(), o === a.enum.PURCHASING_REQUIREMENT_ERROR && /* @__PURE__ */ e.createElement(Ee, { unmatchedItems: h, onCloseDialog: this.closeDialog }), o === a.enum.DOWNLOAD_LAUNCHER && /* @__PURE__ */ e.createElement(
        de,
        {
          item: P,
          isDialogOpen: o === a.enum.DOWNLOAD_LAUNCHER,
          onCloseDialog: this.closeDialog
        }
      ), o === a.enum.CLAIM_SUCCESS && /* @__PURE__ */ e.createElement(
        he,
        {
          item: P,
          itemPublishingContent: n,
          onCloseDialog: this.closeDialog,
          renderLauncherGoToLibraryButton: this.renderLauncherGoToLibraryButton
        }
      ), o === a.enum.CLAIM_FAILED && /* @__PURE__ */ e.createElement(pe, { onCloseDialog: this.closeDialog }), o === a.enum.PAYMENT_SUCCESS && p && /* @__PURE__ */ e.createElement(me, { orderInfo: p, onCloseDialog: this.closeDialog }), i && /* @__PURE__ */ e.createElement("div", { className: "loadingContainer" }, /* @__PURE__ */ e.createElement(X, null)), !i && this.renderPurchaseWidgetContent(), this.renderPendingOrderAlert(), c && /* @__PURE__ */ e.createElement(Re, { error: c }), this.isUserBanned() && !i && !this.itemIsOwned() && /* @__PURE__ */ e.createElement(Ie, null));
    }
  },
  (b, n) => b.item !== n.item
), Re = ({ error: b }) => /* @__PURE__ */ e.createElement("div", null, (() => Q.isAxiosServerError(b) ? /* @__PURE__ */ e.createElement("div", null, /* @__PURE__ */ e.createElement(s, { i18nKey: "CatalogPurchaseWidget.fetchError.serverError" }, "Unable to retrieve entitlement and price information. Please refresh or go back and try again.")) : Q.isAxiosNetworkError(b) ? /* @__PURE__ */ e.createElement("div", null, /* @__PURE__ */ e.createElement(s, { i18nKey: "CatalogPurchaseWidget.fetchError.networkError" }, "Looks like you aren`t connected to the internet. Please check your connection and try again.")) : /* @__PURE__ */ e.createElement("div", null, /* @__PURE__ */ e.createElement(s, { i18nKey: "CatalogPurchaseWidget.fetchError.unknownError" }, "Something went wrong. Please contact support for assistance.")))());
export {
  ft as CatalogPurchaseWidget
};
