import { Ctx as u } from "./accelbyte-widgets33.mjs";
import { OrderAppManager as p } from "./accelbyte-widgets403.mjs";
import { Container as m } from "unstated";
import { EligibleUser as h } from "@accelbyte/sdk-iam";
import { Platform as r } from "@accelbyte/sdk-platform";
import { RegionDataItemHelper as a } from "./accelbyte-widgets388.mjs";
class P extends m {
  constructor(t) {
    super(), this.props = t, this.state = {
      bundleItem: null,
      itemsInBundle: [],
      baseApp: null,
      isFetching: !1,
      error: null,
      itemPublishingContent: null,
      itemPublishingContentError: null
    }, this.sdk = u.getAppState().getSdk();
  }
  async init() {
    try {
      if (this.state.isFetching)
        return;
      this.setState({
        isFetching: !0,
        bundleItem: null,
        itemsInBundle: [],
        error: null
      });
      const t = await this.fetchBundleItem();
      await this.initPurchaseLogic(t);
      const e = await this.fetchItemsInBundle(t.itemIds || []);
      let s = null;
      const { baseAppId: i } = t;
      i && (s = e.find((n) => i === n.appId) || await this.fetchBaseApp(i)), this.setState({
        bundleItem: t,
        itemsInBundle: e,
        baseApp: s,
        itemPublishingContent: null
      });
    } catch (t) {
      console.error(t), this.setState({ error: t });
    } finally {
      this.setState({ isFetching: !1 });
    }
  }
  async fetchBundleItem() {
    const { itemId: t, country: e, language: s } = this.props, i = r.ItemApi(this.sdk), n = await i.getLocale_ByItemId(t, { language: s, region: e });
    if (n.flexible) {
      const o = await i.getItemsEstimatedPrice({ itemIds: n.itemId }), { estimatedPrices: l } = o[0], c = a.getEstimatedPriceMap(l);
      return a.buildRegionDataWithEstimatedPrice(n, c);
    }
    return n;
  }
  async fetchItemsInBundle(t) {
    if (t.length === 0)
      return [];
    const { language: e, country: s } = this.props;
    return await r.ItemApi(this.sdk).getItemsLocaleByIds({
      language: e,
      region: s,
      itemIds: t.toString()
    });
  }
  async fetchBaseApp(t) {
    return await r.ItemApi(this.sdk).getItemsByAppId({
      appId: t,
      region: this.props.country,
      language: this.props.language
    });
  }
  async initPurchaseLogic(t) {
    const { user: e } = this.props, s = this.purchaseLogic = new p(this.sdk, {
      item: t,
      userId: h.safeParse(e).success && (e == null ? void 0 : e.userId) || null
    });
    s.subscribe(() => this.setState({})), await s.init();
    const { fetchError: i } = s.state;
    if (i)
      throw i;
  }
}
export {
  P as BundleItemDetailPageLogic
};
