/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
import { c as g } from "../../chunks/runtime.js";
import { css as f, html as b } from "lit";
import { u as v } from "../../chunks/useT9n.js";
import { LitElement as C, createEvent as n, safeClassMap as _ } from "@arcgis/lumina";
import { T as p } from "../../chunks/solutions-deploy-app-nav.js";
import { a as S, A as w, G as F, F as D, B as x, e as I, T as c } from "../../chunks/interfaces.js";
import { createRef as o, ref as l } from "lit-html/directives/ref.js";
import { C as y, g as O } from "../../chunks/cardFetchingUtils.js";
import { useContextProvider as T } from "@arcgis/lumina/context";
import { h as E, f as k } from "../../chunks/cardsHelpers.js";
import "@esri/solution-common";
import "@arcgis/core/identity/IdentityManager.js";
import "@arcgis/core/identity/OAuthInfo.js";
import "@arcgis/core/portal/Portal.js";
import { _ as A } from "../../chunks/solution-deploy-dialog.js";
import "../solutions-all-shell/customElement.js";
import "../solutions-deployed-shell/customElement.js";
import "../solution-details-panel/customElement.js";
import "../solution-deployed-card-panel/customElement.js";
const M = f`.back-color-override{background-color:var(--calcite-color-foreground-2);--calcite-tab-border-color: var(--calcite-color-foreground-3)}.display-none{display:none!important}.height-100{height:100%}calcite-tab-nav{padding-bottom:6px;padding-top:6px}calcite-tab{--calcite-color-focus: transparent}calcite-tab>*{--calcite-color-focus: initial}calcite-tabs{--calcite-tab-border-color: var(--calcite-color-border-3);height:100%}.tab-space-0{--calcite-tab-content-space-y: var(--calcite-spacing-none)}.tab-space-md{--calcite-tab-content-space-y: var(--calcite-spacing-md)}solutions-searchsort-toolbar,solutions-deploy-app-nav,solution-details-panel,solutions-resources-shell,solutions-deployed-shell,solutions-all-shell,calcite-tab-nav,solution-deployed-card-panel{width:1440px;display:block;max-width:96vw;padding-right:var(--calcite-spacing-none);padding-left:var(--calcite-spacing-none);margin-left:auto;margin-right:auto;box-sizing:border-box}.border{height:var(--calcite-spacing-px);border-bottom-color:var(--calcite-color-border-3);border-bottom-style:solid;border-bottom-width:var(--calcite-border-width-sm);box-sizing:border-box}.overflow-auto{overflow:auto}solution-details-panel{scroll-margin-top:3rem}`;
class L extends C {
  constructor() {
    super(), this.initTitleOrId = "", this.sortType = "relevance", this.useLocalAppConfig = !1, this.authentication = void 0, this._isLoaded = !1, this.isMobile = !1, this._activeTab = "all-solutions", this._showDeployedCardFetchFailed = !1, this._translations = v({ name: "solutions-deploy-app", blocking: !0 }), this._agoTerms = `${S}`, this._allCards = [], this._allShell = o(), this._allTab = o(), this._allTabTitle = o(), this._resourcesTab = o(), this._resourcesTabTitle = o(), this._categories = [], this._configContextProvider = T({ context: w }), this._delay = !1, this._deployAppNav = o(), this._deployedCardPanel = o(), this._deployCardFetchFailedMessage = "", this._deployedCardTab = o(), this._deployedCardTabTitle = o(), this._detailsShell = o(), this._detailsTab = o(), this._detailsTabTitle = o(), this._forceInit = !1, this._getSuggested = !1, this._tabpanelsFixed = !1, this._isMobileContextProvider = T({ context: F }), this._mySolutionsShell = o(), this._mySolutionsTab = o(), this._mySolutionsTabTitle = o(), this._sortField = "relevance", this._sortOrder = "desc", this._telemetryManager = new p(), this.deployAppTabSelected = n(), this.deployedCardFetchFailed = n(), this.detailsCardSelected = n(), this.deployedCardSelected = n(), this.metaTagStringsReady = n(), this.sessionRefreshed = n(), this.tabChanged = n(), this.listenOn(window, "detailsCardSelected", this._detailsCardSelected), this.listenOn(window, "deployedCardSelected", this._deployedCardSelected), this.listenOn(window, "displayDeployedCard", this._handleDeployedCardDisplay), this.listenOn(window, "navTabSelected", this._setActiveTab), this.listenOn(window, "forceSelectTab", (t) => this.selectTab(t.detail, {})), this._mediaQueryChange = this._mediaQueryChange.bind(this);
  }
  static {
    this.properties = { appConfig: 1, initTab: 1, initTitleOrId: 1, sortType: 1, useLocalAppConfig: 5, authentication: 16, _isLoaded: 16, isMobile: 16, _activeTab: 16, _showDeployedCardFetchFailed: 16, _translations: 16 };
  }
  static {
    this.styles = M;
  }
  get _telemetry() {
    return this._configContextProvider.value?.telemetrySession;
  }
  get _isDisconnectedEnvironment() {
    return this._configContextProvider.value?.isEnterprise === !0 && this._configContextProvider.value?.authentication?.CanSearchArcGISOnline === !1;
  }
  async selectTab(t, e) {
    if (this._isLoaded || this._forceInit) {
      const i = this._getDefaultSearchOptions(e);
      switch (this._searchSortToolbar && (this._searchSortToolbar.scope = t.tabType), t.tabType) {
        case "all-solutions":
          this._allTab.value.selected = !0, this._allTabTitle.value.selected = !0, i && await this._allShell.value?.searchSolutions(i);
          break;
        case "resources":
          this._resourcesTab.value.selected = !0, this._resourcesTabTitle.value.selected = !0;
          break;
        case "deployed-card":
          if (this.authentication?.IsSignedIn) {
            if (this._forceInit = !0, this._isLoaded = !1, this._cardFetcherDeployed && await this._getDeployedSolution(t.tabTitleOrId), this._deployedSolutions?.cards?.length > 0) {
              let s;
              this._deployedSolutions.cards.some((a) => a.id === t.tabTitleOrId ? (s = a, this.deployedCardSelected.emit({ card: s }), !0) : !1), this._isLoaded = !0, this._forceInit = !1;
            } else
              return this._isLoaded = !0, this._forceInit = !1, this.selectTab({ tabTitleOrId: "", tabType: "deployments" }, e);
            break;
          } else
            await this.authentication?.signIn();
        case "details":
          if (this._allCards) {
            let s = E(this._allCards, t.tabTitleOrId);
            s = s || k(this._allCards, t.tabTitleOrId), s ? (this._detailsTab.value.selected = !0, this._detailsTabTitle.value.selected = !0, this.detailsCardSelected.emit(s)) : (t.tabType = "all-solutions", this._allTab.value.selected = !0, this._allTabTitle.value.selected = !0);
          }
          break;
        case "deployments":
          this._mySolutionsTab.value.selected = !0, this._mySolutionsTabTitle.value.selected = !0, this._searchSortToolbar && i?.filter && this._searchSortToolbar.changeOwnerFilter(i.filter !== "Organization"), i && await this._mySolutionsShell.value?.searchSolutions(i);
          break;
      }
      return this._setActiveTab(new CustomEvent("setActiveTab", { detail: t })), this._blurTabs(), this._showDeployedCardFetchFailed && (this.deployedCardFetchFailed.emit({ message: this._deployCardFetchFailedMessage, title: this._translations.failedToOpen }), this._showDeployedCardFetchFailed = !1), !0;
    } else
      return this._initTab = t, this._initFilters = e, !1;
  }
  async connectedCallback() {
    super.connectedCallback(), this._mediaQuery = window.matchMedia("(max-width: 800px)"), this._mediaQuery.addEventListener("change", this._mediaQueryChange), this._mediaQueryChange(this._mediaQuery);
  }
  updated() {
    this._fixTabpanelFocus();
  }
  _fixTabpanelFocus() {
    if (!this._tabpanelsFixed && this._allTab.value) {
      const t = [this._allTab, this._mySolutionsTab, this._resourcesTab, this._detailsTab, this._deployedCardTab];
      Promise.all(t.map(async (e) => {
        const i = e.value;
        if (i && (await i.componentOnReady?.(), i.shadowRoot)) {
          const s = i.shadowRoot.querySelector('[role="tabpanel"]');
          s && (s.tabIndex = -1);
        }
      })).then(() => {
        this._tabpanelsFixed = !0, this._setupTabpanelObserver();
      }).catch(() => {
        this._tabpanelsFixed = !0;
      });
    }
  }
  _setupTabpanelObserver() {
    if (this._tabpanelObserver)
      return;
    this._tabpanelObserver = new MutationObserver((e) => {
      e.forEach((i) => {
        if (i.type === "attributes" && i.attributeName === "tabindex") {
          const s = i.target;
          s.getAttribute("role") === "tabpanel" && s.tabIndex === 0 && (s.tabIndex = -1);
        }
      });
    }), [this._allTab, this._mySolutionsTab, this._resourcesTab, this._detailsTab, this._deployedCardTab].forEach((e) => {
      const i = e.value;
      if (i?.shadowRoot) {
        const s = i.shadowRoot.querySelector('[role="tabpanel"]');
        s && this._tabpanelObserver.observe(s, { attributes: !0, attributeFilter: ["tabindex"] });
      }
    });
  }
  async load() {
    this.useLocalAppConfig && (this.appConfig = A);
  }
  render() {
    const t = this._isLoaded ? "display-none" : "", e = this._isLoaded ? "" : "display-none";
    return b`<calcite-shell><solutions-deploy-app-nav .appConfig=${this.appConfig} .initTab=${this.initTab} @authInit=${this._handleAuthInit} slot=header ${l(this._deployAppNav)}></solutions-deploy-app-nav>${this._isSearchToolbarShowing() && b`<div class="border" slot=header></div>` || ""}<solutions-searchsort-toolbar slot=header ${l(async (i) => {
      i && (await this._deployAppNav.value?.componentOnReady(), this._searchSortToolbar = i);
    })}></solutions-searchsort-toolbar><calcite-loader class=${_(t)} id=solutions-loader .label=${this._translations.fetchingAllSolutions}></calcite-loader><calcite-tabs class=${_(e)} scale=l><calcite-tab-nav class="display-none" @calciteTabChange=${this._handleCalciteTabChanged} slot=title-group><calcite-tab-title ${l(this._allTabTitle)}>${this._translations.allSolutions}</calcite-tab-title><calcite-tab-title ${l(this._mySolutionsTabTitle)}>${this._translations.mySolutions}</calcite-tab-title><calcite-tab-title ${l(this._resourcesTabTitle)}>${this._translations.solutionResources}</calcite-tab-title><calcite-tab-title class="display-none" ${l(this._detailsTabTitle)}></calcite-tab-title><calcite-tab-title class="display-none" ${l(this._deployedCardTabTitle)}></calcite-tab-title></calcite-tab-nav><calcite-tab class="back-color-override tab-space-0" selected ${l(this._allTab)}><solutions-all-shell class="height-100" ${l(this._allShell)}></solutions-all-shell></calcite-tab><calcite-tab class="back-color-override tab-space-0" ${l(this._mySolutionsTab)}><solutions-deployed-shell class="height-100" ${l(this._mySolutionsShell)}></solutions-deployed-shell></calcite-tab><calcite-tab class="back-color-override tab-space-0" ${l(this._resourcesTab)}><solutions-resources-shell class="height-100"></solutions-resources-shell></calcite-tab><calcite-tab class="back-color-override" ${l(this._detailsTab)}><solution-details-panel class="height-100" ${l(this._detailsShell)}></solution-details-panel></calcite-tab><calcite-tab class="back-color-override tab-space-0" ${l(this._deployedCardTab)}><solution-deployed-card-panel class="shell-container height-100" ${l(this._deployedCardPanel)}></solution-deployed-card-panel></calcite-tab></calcite-tabs></calcite-shell>`;
  }
  loaded() {
    this._setScrollbarGutters();
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this._mediaQuery?.removeEventListener("change", this._mediaQueryChange), this._tabpanelObserver?.disconnect();
  }
  async _handleAuthInit(t) {
    const e = t.detail;
    e.telemetrySession || (e.telemetrySession = p.getDisabledSession()), this._configContextProvider.setValue(e), e.authentication && (this.authentication = e.authentication), this._cardFetcherDeployed = new y(e.locale, e.orgUrl, e.portalURL), this._cardsFetcher = new y(e.locale, e.orgUrl, e.portalURL), this._isDisconnectedEnvironment || await this._getSolutions(e.primarySolutionsGroupId, e.agoBasedEnterpriseSolutionsGroupId), this._configContextProvider.value.allCards = this._allCards, this._configContextProvider.value.anonAgolSession = this._cardsFetcher.anonAgolSession, this._configContextProvider.value.agolPortalUrl = this._cardsFetcher.agolPortalUrl, await this._initializeTelemetry(), this._isLoaded = !0, this._setRefreshInterval(), this._initTab ? (this.selectTab(this._initTab, this._initFilters), this._logTabViewTelemetry(this._initTab.tabType), this._initTab = void 0, this._initFilters = void 0) : this.authentication?.IsSignedIn && (this.initTab === "details" || this.initTab === "deployed-card" || (this._logTabViewTelemetry(this._activeTab), this._emitMetaTagStrings(this._activeTab)));
  }
  _mediaQueryChange(t) {
    this.isMobile = t.matches, this._isMobileContextProvider.setValue(this.isMobile);
  }
  _setActiveTab(t) {
    const i = t.detail.tabType, s = this._activeTab !== i;
    switch (this._activeTab = i, s && this._logTabViewTelemetry(i), i) {
      case "all-solutions":
        this._allTabTitle.value?.click();
        break;
      case "deployments":
        this._mySolutionsTabTitle.value?.click();
        break;
      case "resources":
        this._resourcesTabTitle.value?.click();
        break;
      case "deployed-card":
        this._deployedCardTabTitle.value?.click();
        break;
      case "details":
        this._detailsTabTitle.value?.click();
        break;
    }
    i !== "details" && i !== "deployed-card" && (this._deployAppNav.value.activateMenuItem(i), this.deployAppTabSelected.emit(i), this._emitMetaTagStrings(i));
  }
  _logTabViewTelemetry(t, e) {
    let i;
    switch (t) {
      case "all-solutions":
        i = c.ALL_SOLUTIONS;
        break;
      case "deployments":
        i = c.DEPLOYMENTS;
        break;
      case "resources":
        i = c.RESOURCES;
        break;
      case "details":
        i = c.SOLUTION_DETAILS;
        break;
      case "deployed-card":
        i = c.DEPLOYMENTS;
        break;
    }
    if (!((t === "details" || t === "deployed-card") && !e) && i) {
      const s = [];
      if ((t === "details" || t === "deployed-card") && e) {
        const r = e;
        s.push(r.title || ""), s.push(r.deployCommonId || ""), s.push(r.deployVersion || "");
      }
      const a = t === "deployed-card" ? "Open" : "View";
      this._telemetry?.logEvent({
        category: i,
        action: a,
        dimensions: s.length > 0 ? s : void 0
      });
    }
  }
  _emitMetaTagStrings(t, e) {
    let i = "", s = "";
    switch (t) {
      case "all-solutions":
        i = this._translations.metaAllSolutionsTitle, s = this._translations.metaAllSolutionsDescription;
        break;
      case "deployments":
      case "deployed-card":
        i = this._translations.metaDeploymentsTitle, s = this._translations.metaDeploymentsDescription;
        break;
      case "resources":
        i = this._translations.metaResourcesTitle, s = this._translations.metaResourcesDescription;
        break;
      case "details":
        e && (i = this._translations.metaDetailsTitle.replace("{title}", e.title), s = e.snippet);
        break;
    }
    this.metaTagStringsReady.emit({
      pageType: t,
      title: i,
      description: s,
      detailTemplate: e
    });
  }
  _handleCalciteTabChanged() {
    this.tabChanged.emit(this._activeTab);
  }
  _detailsCardSelected(t) {
    this._activeTab = "details", this._detailsTabTitle.value.selected = !0, this._detailsTab.value.selected = !0, this._deployAppNav.value.clearMenuItems(), t?.detail && (this._selectedDetailsCard = t.detail), this._logTabViewTelemetry("details", this._selectedDetailsCard), this._emitMetaTagStrings("details", this._selectedDetailsCard);
  }
  _deployedCardSelected(t) {
    this._activeTab = "deployed-card", this._deployedCardTabTitle.value.selected = !0, this._deployedCardTab.value.selected = !0, this._deployAppNav.value.clearMenuItems(), t?.detail?.card && (this._selectedDeployedCard = t.detail.card), this._logTabViewTelemetry("deployed-card", this._selectedDeployedCard), this._emitMetaTagStrings("deployed-card");
  }
  _handleDeployedCardDisplay(t) {
    const { card: e, cardRef: i } = t.detail;
    this.deployedCardSelected.emit({ card: e, cardRef: i });
  }
  async _initializeTelemetry() {
    const t = this._configContextProvider.value;
    if (!this.authentication || !t)
      return;
    const e = await this._telemetryManager.initializeTelemetry(this.authentication, t);
    this._configContextProvider.value.telemetrySession = e;
  }
  async _getSolutions(t, e) {
    if (this._isDisconnectedEnvironment)
      return [];
    this._abortController ? (this._abortController.abort(), this._abortController = new AbortController()) : this._abortController = new AbortController();
    const i = await this._cardsFetcher?.requestAvailableSolutionCards({
      q: this._agoTerms,
      filter: "type:Solution",
      sortField: this._sortField,
      sortOrder: this._sortOrder,
      // TODO default search when old app loads is desc...may need to switch this for other
      nextStart: -1,
      categories: this._categories,
      delay: this._delay,
      getSuggested: this._getSuggested,
      num: 100
    }, t, e, this._configContextProvider.value.userSession, this._configContextProvider.value.isEnterprise, this._abortController.signal, {
      num: 1e3
    });
    return this._abortController = void 0, this._allCards.length === 0 && i?.cards && (this._allCards = i?.cards), this._allCards;
  }
  async _getDeployedSolution(t) {
    const e = this._configContextProvider.value.authentication, i = this._configContextProvider.value.userSession;
    if (e && i && e.IsSignedIn) {
      this._abortControllerDeployed ? (this._abortControllerDeployed.abort(), this._abortControllerDeployed = new AbortController()) : this._abortControllerDeployed = new AbortController();
      const s = D(e);
      try {
        const a = await O(e, i, this._cardsFetcher, this._cardFetcherDeployed, x, "created", "desc", !1, [], [], this._abortControllerDeployed.signal, s ? "My organization's solutions" : "My solutions", t);
        a.cards.length === 0 || a.cards[0].typeKeywords.indexOf("Deployed") < 0 ? (this._deployCardFetchFailedMessage = this._translations.failedToFetchNotSolution.replace("{{ITEMID}}", t), this._showDeployedCardFetchFailed = !0) : this._deployedSolutions = a;
      } catch (a) {
        const r = a.message;
        r.indexOf("CONT_0001") > -1 || r.indexOf("Item does not exist or is inaccessible.") > -1 ? (this._deployCardFetchFailedMessage = this._translations.failedToFetchWrongId.replace("{{ITEMID}}", t), this._showDeployedCardFetchFailed = !0) : r.indexOf("GWM_0003") > -1 || r.indexOf("You do not have permissions to access this resource or perform this operation.") > -1 ? (this._deployCardFetchFailedMessage = this._translations.failedToFetchWrongPermissions.replace("{{ITEMID}}", t), this._showDeployedCardFetchFailed = !0) : (this._showDeployedCardFetchFailed = !0, this._deployCardFetchFailedMessage = ""), console.warn(a);
      }
    }
  }
  _blurTabs() {
    this._allTabTitle.value?.blur(), this._resourcesTabTitle.value?.blur(), this._detailsTabTitle.value?.blur(), this._mySolutionsTabTitle.value?.blur();
  }
  _isSearchToolbarShowing() {
    return this._activeTab === "all-solutions" || this._activeTab === "deployments" && this.authentication?.IsSignedIn === !0;
  }
  _getDefaultSearchOptions(t) {
    let e;
    if (t) {
      const i = t.domain, s = t.industry === "AEC" ? I.AEC : t.industry, a = t.offerType, r = t.searchTerm, m = "";
      let d = t.sortField;
      const h = t.owner, u = t.filter;
      e = i || s ? {
        type: i ? "domain" : s ? "industry" : ""
      } : void 0, i && (e = e ? { ...e, domain: i } : { domain: i }), s && (e = e ? { ...e, industry: s } : { industry: s }), r && (e = e ? { ...e, searchTerm: r } : { searchTerm: r }), e && (e = { ...e, displayValue: m }), d && (e = e ? { ...e, sortType: d } : { sortType: d }), a && (d = a.toLowerCase(), e = e ? { ...e, sortType: d } : { sortType: d }), h && (e = e ? { ...e, owner: h } : { owner: h }), u && (e = e ? { ...e, filter: u } : { filter: u });
    }
    return e;
  }
  _setScrollbarGutters() {
    const t = this._detailsTab.value?.shadowRoot?.firstElementChild;
    t?.style && (t.style.scrollbarGutter = "stable both-edges");
    const e = this._deployedCardTab.value?.shadowRoot?.firstElementChild;
    e?.style && (e.style.scrollbarGutter = "stable both-edges");
  }
  _setRefreshInterval() {
    const { userSession: t, authentication: e } = this._configContextProvider.value;
    if (t && t.tokenDuration && e?.IsSignedIn) {
      const i = Date.now(), a = (e.Credential?.expires - i) * 0.95;
      setInterval(async () => {
        if (e.Credential && e.Credential.expires) {
          await e.Credential?.refreshToken();
          const r = new Date(e.Credential.expires);
          t.updateToken(e.Credential.token, r), this.sessionRefreshed.emit(t.token);
        }
      }, a);
    }
  }
}
g("solutions-deploy-app", L);
export {
  L as SolutionsDeployApp
};
