import { S as StoreGridItem, O as OrderAppManager, I as ItemDetailPurchaseAlert, C as CatalogItemBanner, B as Breadcrumbs, A as AppDetailGallery, L as Lightbox, a as CatalogOverview, b as CatalogTitleWidget, D as DiscountCountdownWidget, c as CatalogPurchaseWidget } from "./ItemDetailPurchaseAlert.js";
import { C as Container, a as Ctx, L as Loading, w as LoadingSize, i as CommonError, T as Trans, ac as EligibleUser, E as ErrorHelper, q as EcommerceErrorCode, ad as gaSendErrorEvent, r as ErrorPath, F as FeUtils, a2 as EcomPath, t, a7 as ItemType } from "./index.js";
import { I as ItemHelper } from "./ItemHelper.js";
import React__default from "react";
import { a as Helmet } from "./Helmet.js";
import { Link } from "react-router-dom";
import "./CodeStore.js";
import { w as withPropsGuard } from "./WithPropsGuard.js";
import { ItemDetailPageLoadingScreen, ItemDetailPageError } from "./InGameItemDetailPage.js";
import "./reactSlick.js";
import "./dateFns.js";
import "./default-item-image.js";
import "./reactPlayer.js";
import "./SuccessFlatIcon.js";
import "./WarningIcon.js";
import "./PendingOrdersAppManager.js";
import "./PaymentStatusDialog.js";
import "./Radio.js";
import "./validator.js";
import "./CommonError.js";
import "./starBgGradient.js";
import "./CommonError2.js";
var RelatedProductKey$1 = "";
const _RelatedProductKeyLogic = class extends Container {
  constructor(props) {
    super();
    this.props = props;
    this.state = {
      isFetching: false,
      items: null,
      error: null,
      currencyMap: null
    };
    this.sdk = Ctx.getAppState().getSdk();
  }
  async init() {
    try {
      if (this.state.isFetching)
        return;
      await this.setState({
        isFetching: true,
        error: null,
        items: null,
        currencyMap: null
      });
      const items = await this.fetchItems();
      const currencyMap = await this.fetchCurrencyMap();
      this.setState({ items, currencyMap });
    } catch (error) {
      console.error(error);
      this.setState({ error });
    } finally {
      await this.setState({ isFetching: false });
    }
  }
  async fetchItems() {
    const { baseItem, itemType, appType, country, language } = this.props;
    const baseAppId = baseItem.baseAppId || baseItem.appId;
    let hasNext = false;
    let offset = 0;
    let allItems = [];
    do {
      const items = await this.sdk.Platform.Item().fetchItemsByCriteria({
        queryParams: {
          baseAppId,
          itemType,
          appType,
          region: country,
          language,
          offset,
          limit: _RelatedProductKeyLogic.ITEMS_PER_FETCH
        }
      }).then((result) => {
        var _a;
        if (result.error)
          throw result.error;
        hasNext = !!((_a = result.response.data.paging) == null ? void 0 : _a.next);
        offset += _RelatedProductKeyLogic.ITEMS_PER_FETCH;
        return result.response.data.data.filter((item) => item.itemId !== baseItem.itemId);
      });
      allItems = allItems.concat(items);
    } while (hasNext);
    return allItems;
  }
  async fetchCurrencyMap() {
    return this.sdk.Platform.Currency().getCurrencyMap().then((result) => {
      if (result.error)
        throw result.error;
      return result.value;
    });
  }
};
let RelatedProductKeyLogic = _RelatedProductKeyLogic;
RelatedProductKeyLogic.ITEMS_PER_FETCH = 100;
const INITIAL_SHOWN_ITEM = 8;
class RelatedProductKey extends React__default.Component {
  constructor(props) {
    super(props);
    this.initialShownItem = INITIAL_SHOWN_ITEM;
    if (props.initialShownItem) {
      this.initialShownItem = props.initialShownItem;
    }
    this.logic = new RelatedProductKeyLogic({
      baseItem: props.baseItem,
      itemType: props.itemType,
      appType: props.appType,
      country: props.country,
      language: props.language
    });
    this.logic.subscribe(() => this.setState({}));
    this.state = {
      open: false
    };
  }
  componentDidMount() {
    this.logic.init();
  }
  renderContent() {
    const { noItemMessage } = this.props;
    const { items, isFetching, error, currencyMap } = this.logic.state;
    const { open } = this.state;
    return /* @__PURE__ */ React__default.createElement("div", {
      className: "relatedProductKeys list"
    }, /* @__PURE__ */ React__default.createElement("div", {
      className: "relatedProductKeysData"
    }, isFetching && /* @__PURE__ */ React__default.createElement(Loading, {
      className: LoadingSize.medium
    }), error && /* @__PURE__ */ React__default.createElement("div", {
      className: "errorContainer"
    }, /* @__PURE__ */ React__default.createElement(CommonError, {
      error
    })), items && items.length === 0 && /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, noItemMessage, !noItemMessage && /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "RelatedProductKey.grid.empty"
    }, "No Items Available")), /* @__PURE__ */ React__default.createElement("div", {
      className: "relatedProductKeysGrid"
    }, items && currencyMap && (open ? items : items.slice(0, this.initialShownItem)).map((item) => /* @__PURE__ */ React__default.createElement(StoreGridItem, {
      key: item.itemId,
      item,
      currencyMap
    })))), items && items.length > this.initialShownItem && !open && /* @__PURE__ */ React__default.createElement("div", {
      className: "showMoreButton"
    }, /* @__PURE__ */ React__default.createElement("button", {
      className: "btn btn-primary",
      type: "button",
      onClick: () => this.setState({ open: true })
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "RelatedProductKey.showAllButton"
    }, "Show All"))));
  }
  render() {
    const { withWrapper } = this.props;
    const { items, error } = this.logic.state;
    if (!withWrapper) {
      return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, this.renderContent());
    }
    return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, (items && items.length > 0 || error) && withWrapper(this.renderContent()));
  }
}
withPropsGuard((containerProps) => {
  const appState = Ctx.getAppState();
  return /* @__PURE__ */ React__default.createElement(RelatedProductKey, {
    country: (appState.getUser() || { country: void 0 }).country,
    ...containerProps
  });
}, (prevProps, nextProps) => prevProps.baseItem !== nextProps.baseItem || prevProps.country !== nextProps.country);
class CodeItemDetailPageLogic extends Container {
  constructor(props) {
    super();
    this.props = props;
    this.state = {
      codeItem: null,
      itemsInCode: [],
      baseApp: null,
      isFetching: false,
      error: null,
      itemPublishingContent: null,
      itemPublishingContentError: null
    };
    this.sdk = Ctx.getAppState().getSdk();
  }
  setProperties(props) {
    for (const key in props) {
      this.props[key] = props[key];
    }
  }
  async init() {
    try {
      if (this.state.isFetching)
        return;
      this.setState({
        isFetching: true,
        codeItem: null,
        itemsInCode: [],
        error: null
      });
      const bundleItem = await this.fetchBundleItem();
      await this.initPurchaseLogic(bundleItem);
      const itemsInBundle = await this.fetchItemsInCode(bundleItem.itemIds || []);
      let baseApp = null;
      const { baseAppId } = bundleItem;
      if (baseAppId) {
        baseApp = itemsInBundle.find((item) => baseAppId === item.appId) || await this.fetchBaseApp(baseAppId);
      }
      this.setState({
        codeItem: bundleItem,
        itemsInCode: itemsInBundle,
        baseApp,
        itemPublishingContent: null
      });
    } catch (error) {
      console.error(error);
      this.setState({ error });
    } finally {
      this.setState({ isFetching: false });
    }
  }
  async fetchBundleItem() {
    const { itemId, country, language } = this.props;
    return await this.sdk.Platform.Item().getItemsByItemIdLocale({ itemId, queryParams: { language, region: country } }).then((result) => {
      if (result.error)
        throw result.error;
      return result.response.data;
    });
  }
  async fetchItemsInCode(itemIds) {
    if (itemIds.length === 0)
      return [];
    const { language, country } = this.props;
    return await this.sdk.Platform.Item().getItemsByItemIds({
      queryParams: { language, itemIds: itemIds.toString(), region: country }
    }).then((result) => {
      if (result.error)
        throw result.error;
      return result.response.data;
    });
  }
  async fetchBaseApp(baseAppId) {
    return await this.sdk.Platform.Item().getItemByAppId({
      appId: baseAppId,
      region: this.props.country,
      language: this.props.language
    }).then((result) => {
      if (result.error)
        throw result.error;
      return result.response.data;
    });
  }
  async initPurchaseLogic(item) {
    const { user } = this.props;
    const purchaseLogic = this.purchaseLogic = new OrderAppManager(this.sdk, {
      item,
      userId: EligibleUser.safeParse(user).success && (user == null ? void 0 : user.userId) || null
    });
    purchaseLogic.subscribe(() => this.setState({}));
    await purchaseLogic.init();
    const { fetchError } = purchaseLogic.state;
    if (fetchError)
      throw fetchError;
  }
}
class CodeItemDetailPage extends React__default.Component {
  constructor(props) {
    super(props);
    this.openLightbox = (selectedImagePosition) => {
      this.setState({ isLightboxOpen: true, selectedImagePosition });
    };
    this.closeLightbox = () => {
      this.setState({ isLightboxOpen: false });
    };
    const { itemId, country, language, user } = this.props;
    this.logic = new CodeItemDetailPageLogic({ itemId, country, language, user });
    this.logic.subscribe(() => this.setState({}));
    this.state = {
      isLightboxOpen: false,
      selectedImagePosition: 0
    };
  }
  async componentDidMount() {
    await this.initialize();
  }
  async componentDidUpdate(prevProps) {
    if (prevProps.itemId !== this.props.itemId || prevProps.language !== this.props.language) {
      await this.initialize();
    }
  }
  async initialize() {
    this.logic.setProperties(this.props);
    await this.logic.init();
  }
  render() {
    const { user } = this.props;
    const { isFetching, codeItem, error, baseApp, itemPublishingContent } = this.logic.state;
    if (error && ErrorHelper.extractServiceErrorCode(error) === EcommerceErrorCode.ITEM_NOT_FOUND) {
      gaSendErrorEvent({ eventCategory: ErrorPath.Error404.makePath(), eventLabel: ErrorHelper.errorToString(error) });
    }
    const { purchaseLogic } = this.logic;
    const currencyMap = purchaseLogic && purchaseLogic.state.currencyMap;
    const { isLightboxOpen, selectedImagePosition } = this.state;
    const itemMedias = ItemHelper.getMedia(codeItem, itemPublishingContent);
    return /* @__PURE__ */ React__default.createElement("main", {
      className: "itemDetailPage"
    }, /* @__PURE__ */ React__default.createElement(ItemDetailPurchaseAlert, {
      ...{
        purchaseLogic,
        user,
        isFetching
      }
    }), /* @__PURE__ */ React__default.createElement(Helmet, null, codeItem && /* @__PURE__ */ React__default.createElement("title", null, FeUtils.makeTitleWithAppName(codeItem.title))), isFetching && /* @__PURE__ */ React__default.createElement(ItemDetailPageLoadingScreen, null), error && /* @__PURE__ */ React__default.createElement(ItemDetailPageError, {
      error
    }), codeItem && /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, /* @__PURE__ */ React__default.createElement(CatalogItemBanner, {
      item: codeItem,
      itemPublishingContent
    }, /* @__PURE__ */ React__default.createElement(Breadcrumbs, null, /* @__PURE__ */ React__default.createElement(Link, {
      to: EcomPath.CodeList.makePath()
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "Navigation.links.productKeys"
    }, "Product Keys")), baseApp && /* @__PURE__ */ React__default.createElement(Link, {
      to: EcomPath.getItemDetailRoute(baseApp)
    }, baseApp.title), codeItem.title)), itemMedias && /* @__PURE__ */ React__default.createElement(AppDetailGallery, {
      itemMedias,
      openLightbox: this.openLightbox
    }), isLightboxOpen && itemMedias && /* @__PURE__ */ React__default.createElement(Lightbox, {
      itemMedias,
      isOpen: isLightboxOpen,
      onClose: this.closeLightbox,
      selectedPosition: selectedImagePosition
    }), /* @__PURE__ */ React__default.createElement("div", {
      className: "itemDetailContent"
    }, /* @__PURE__ */ React__default.createElement("div", {
      className: "description"
    }, /* @__PURE__ */ React__default.createElement(CatalogOverview, {
      item: codeItem
    })), /* @__PURE__ */ React__default.createElement("div", {
      className: "detailWidget"
    }, /* @__PURE__ */ React__default.createElement(CatalogTitleWidget, {
      item: codeItem,
      tag: t("CodeItemDetailPage.tag")
    }, currencyMap && /* @__PURE__ */ React__default.createElement(DiscountCountdownWidget, {
      item: codeItem,
      currencyMap,
      position: "right",
      showDetail: true
    })), /* @__PURE__ */ React__default.createElement("div", {
      className: "protruded"
    }, /* @__PURE__ */ React__default.createElement(CatalogPurchaseWidget, {
      item: codeItem,
      purchaseLogic
    })), baseApp && /* @__PURE__ */ React__default.createElement("div", {
      className: "requiredApp"
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "CodeItemDetailPage.requiredAppNotice"
    }, "Required Game"), /* @__PURE__ */ React__default.createElement(Link, {
      to: EcomPath.getItemDetailRoute(baseApp)
    }, baseApp.title)))), /* @__PURE__ */ React__default.createElement("div", {
      className: "storeContainer"
    }, /* @__PURE__ */ React__default.createElement("h2", null, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "CodeItemDetailPage.inAppStore.heading"
    }, "Related Items")), /* @__PURE__ */ React__default.createElement(RelatedProductKey, {
      baseItem: codeItem,
      language: this.props.language,
      itemType: ItemType.enum.CODE,
      noItemMessage: /* @__PURE__ */ React__default.createElement("div", {
        className: "noItem"
      }, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "CodeItemDetailPage.inAppStore.noItem"
      }, "Looks like there are no related items yet."))
    }))));
  }
}
var CodeItemDetailPage$1 = React__default.memo((props) => {
  const { itemId, language } = props;
  const user = Ctx.getAppState().getUser() || void 0;
  const country = user && user.country || void 0;
  return /* @__PURE__ */ React__default.createElement(CodeItemDetailPage, {
    itemId,
    country,
    user,
    language
  });
}, (prevProps, nextProps) => prevProps.itemId === nextProps.itemId && nextProps.language === prevProps.language);
export { CodeItemDetailPage$1 as default };
