/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { c as f } from "../../chunks/runtime.js";
import { css as y, html as d, svg as C } from "lit";
import { u as S } from "../../chunks/useT9n.js";
import { LitElement as w, createEvent as h } from "@arcgis/lumina";
import { useContextConsumer as v } from "@arcgis/lumina/context";
import { a as _, T as g, B as x, d as T, e as I } from "../../chunks/interfaces.js";
import { C as p } from "../../chunks/CardsFetcher.js";
import { g as A } from "../../chunks/cardsHelpers.js";
import { g as E } from "../../chunks/cardFetchingUtils.js";
import { c as b } from "../../chunks/deployAppContexts.js";
import { o as D, l as L } from "../../chunks/helpers.js";
const F = y`calcite-panel{width:100%;height:100%;display:flex;flex-direction:column;min-height:0;--calcite-panel-background-color: var(--calcite-color-surface-3)}.card-group{flex:1;min-height:0;overflow:auto;padding:.25rem var(--calcite-spacing-md) var(--calcite-spacing-md)}solution-details-card{width:calc(25% - .6rem)}@container (max-width: 1234px){solution-details-card{width:calc(33.333% - .6rem)}}@container (max-width: 1010px){solution-details-card{width:calc(50% - .6rem)}}@container (max-width: 800px){.card-group{padding-left:0;padding-right:0}solution-details-card{width:calc(33.33% - .6rem)}}@container (max-width: 680px){solution-details-card{width:calc(50% - .6rem)}}@container (max-width: 440px){solution-details-card{width:calc(100% - .75rem)}}.text-center{text-align:center}.leader-1{margin-top:var(--calcite-spacing-xxl)}.trailer-1{margin-bottom:var(--calcite-spacing-xxl)}.warning-text{max-width:35em;margin-left:auto;margin-right:auto;font-size:var(--calcite-font-size-md)}.no-solutions{display:flex;flex-direction:column;justify-content:center;align-items:center;width:100%;min-height:calc(100vh - 190px)}.margin-top-half{margin-top:.5rem}.margin-top-1{margin-top:1rem}.no-solutions-prompt{display:flex;flex-direction:column;justify-content:center;align-items:center;width:100%}`, m = 5;
class $ extends w {
  constructor() {
    super(), this.sortType = "relevance", this._cards = [], this._isLoading = !0, this._modifiedCheckTry = 0, this._translations = S({ name: "solutions-all-panel", blocking: !0 }), this._agoTerms = `${_}`, this._allCards = [], this._baseAgoTerms = _, this._categories = [], this._configContextConsumer = v({
      context: b,
      subscribe: !0,
      callback: async (e) => {
        e && (this._isDisconnectedEnvironment ? this._isLoading = !1 : await this._loadUpdateProcedures());
      }
    }), this._delay = !1, this._getSuggested = !1, this._relatedSolutions = /* @__PURE__ */ new Set(), this._sortField = "relevance", this._sortOrder = "desc", this._assistantSolutionIds = /* @__PURE__ */ new Set(), this.cardsFetched = h(), this.allCardsFetched = h(), this.searchTermSet = h(), this.sortTypeSet = h(), this.detailsCardSelected = h(), this._handleOpenAssistant = () => {
      this._telemetry?.logEvent({
        category: g.ASSISTANT,
        action: "Open"
      }), window.dispatchEvent(new CustomEvent("openAssistant"));
    }, this.listenOn(window, "deployProgressEnd", () => {
      this._modifiedCheckTry = m, this._loadUpdateProcedures();
    }), this.listenOn(window, "solutionDeleted", () => {
      this._modifiedCheckTry = m, this._loadUpdateProcedures();
    }), this.listenOn(window, "sortTypeChanged", (e) => {
      e.detail && e.detail.scope === "all-solutions" && (this.sortType = e.detail.sortType, this._telemetry?.logEvent({
        category: g.ALL_SOLUTIONS,
        action: "Sort",
        dimensions: [D(e.detail.sortType)]
      }), this.sortType === "suggested" && this._deployedSolutions?.cards.length === 0 ? this._getDeployedSolutions().then(() => {
        this.searchSolutions(e.detail);
      }) : this.searchSolutions(e.detail));
    }), this.listenOn(window, "solutionIDFromAssistant", (e) => {
      this._lookupSolutionById(e.detail);
    }), this.listenOn(window, "solutionMatchesFromAssistant", (e) => {
      this._applyAssistantSolutionMatches(e.detail);
    }), this.listenOn(window, "clearAssistantResultFilters", () => {
      this._assistantSolutionIds = /* @__PURE__ */ new Set();
    });
  }
  static {
    this.properties = { sortType: 1, _cards: 16, _isLoading: 16, _modifiedCheckTry: 16, _translations: 16 };
  }
  static {
    this.styles = F;
  }
  get _isEnterprise() {
    return this._configContextConsumer.value?.isEnterprise;
  }
  get _telemetry() {
    return this._configContextConsumer.value?.telemetrySession;
  }
  get _isDisconnectedEnvironment() {
    return this._configContextConsumer.value?.isEnterprise === !0 && this._configContextConsumer.value?.authentication?.CanSearchArcGISOnline === !1;
  }
  async searchSolutions(e) {
    this._isDisconnectedEnvironment || (e ? "searchTerm" in e ? this._textSearch(e.searchTerm) : "sortType" in e ? this._sortCards(e) : Array.isArray(e) && this._filterCards(e) : (this._agoTerms = this._baseAgoTerms, this._clearFilterCategories()), this._cards = await this._getSolutions());
  }
  async setSearchOptions(e) {
    e && ("searchTerm" in e && (this._textSearch(e.searchTerm), this.searchTermSet.emit({
      searchTerm: e.searchTerm,
      scope: "all-solutions"
    })), "sortType" in e && (this._sortCards(e), this.sortTypeSet.emit({
      sortType: e.sortType,
      scope: "all-solutions"
    })));
  }
  getDisplayedSolutionIds() {
    return this._cards.map((e) => e.deployCommonId);
  }
  render() {
    const e = this._configContextConsumer.value?.authentication?.IsSignedIn && this._configContextConsumer.value?.authentication?.CanUseAI;
    return this._isDisconnectedEnvironment ? d`<div class="no-solutions">${this._getMeridianSearch()}<div class="no-solutions-prompt"><div class="text-center leader-1 warning-text trailer-1"><div>${this._translations.disconnectedEnvironment}</div></div></div></div>` : this._isLoading || this._cards.length ? d`<calcite-panel>${this._isLoading ? d`<calcite-loader id=solutions-all-panel-loader .label=${this._translations.fetchingSolutions}></calcite-loader>` : d`<calcite-card-group class="card-group" .label=${this._translations.allSolutionCards}>${this._renderCards()}</calcite-card-group>`}</calcite-panel>` : d`<div class="no-solutions">${this._getMeridianSearch()}<div class="no-solutions-prompt"><div class="text-center leader-1 warning-text trailer-1"><div>${this._translations.noSolutionsFound}</div><div class="margin-top-half">${!this._isEnterprise && e ? this._translations.assistantHelp : this._translations.changeSearchTerm}</div></div>${!this._isEnterprise && e && d`<calcite-button appearance=outline icon-start=speech-bubbles @click=${this._handleOpenAssistant} @keydown=${(t) => L(t, () => this._handleOpenAssistant())} scale=l>${this._translations.askAssistant}</calcite-button>` || ""}</div></div>`;
  }
  _renderCards() {
    return this._cards.map((e) => d`<solution-details-card .card=${e}></solution-details-card>`);
  }
  async _getSolutions() {
    if (this._isDisconnectedEnvironment)
      return this._isLoading = !1, [];
    if (this._configContextConsumer.value) {
      this._isLoading = !0, this._abortController ? (this._abortController.abort(), this._abortController = new AbortController()) : this._abortController = new AbortController();
      const e = 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
      }, this._configContextConsumer.value?.primarySolutionsGroupId, this._configContextConsumer.value?.agoBasedEnterpriseSolutionsGroupId, this._configContextConsumer.value?.userSession, this._configContextConsumer.value?.isEnterprise, this._abortController.signal, {
        num: 1e3
      });
      this._abortController = void 0;
      const t = e?.cards.length ? e.cards : [];
      if (this.sortType === "new" || this.sortType === "updated") {
        let s = "/Categories/New Release";
        this.sortType === "updated" && (s = "/Categories/Updated"), t.sort((a, l) => a.categories.includes(s) && !l.categories.includes(s) ? -1 : !a.categories.includes(s) && l.categories.includes(s) ? 1 : a.categories.includes(s) && l.categories.includes(s) ? a.categories.length - l.categories.length : 0);
      } else if (this.sortType === "suggested" && this._relatedSolutions.size > 0 && this._deployedSolutions?.cards?.length) {
        const s = /* @__PURE__ */ new Map();
        for (const o of t) {
          const n = s.get(o.deployCommonId), r = Number(o.deployVersion);
          (!n || r > n) && s.set(o.deployCommonId, r);
        }
        const a = this._deployedSolutions.cards.filter((o) => {
          const n = s.get(o.deployCommonId);
          return n !== void 0 && Number(o.deployVersion) >= n;
        }), l = new Set(a.map((o) => o.deployCommonId));
        this._relatedSolutions = new Set([...this._relatedSolutions].filter((o) => !l.has(o))), t.sort((o, n) => {
          const r = this._relatedSolutions.has(o.deployCommonId), u = this._relatedSolutions.has(n.deployCommonId);
          return r && !u ? -1 : !r && u ? 1 : 0;
        });
      }
      const i = t.map((s) => {
        const a = s.categories.indexOf("/Categories/New Release") > -1, l = s.categories.indexOf("/Categories/Updated") > -1;
        let o = !1, n = !0;
        this._deployedSolutions && (o = this._isSolutionDeployed(s.deployCommonId), n = this._isLatestVersion(s));
        const r = [];
        return a ? r.push("new") : l && r.push("updated"), o && (n ? r.push("deployed") : r.push("deployedOlderVersion")), s.chips = r.length > 0 ? r : void 0, s.supportReuse = o ? !!(o && !n) : !0, s;
      });
      this._allCards.length === 0 && e?.cards && (this._allCards = e?.cards, this._deployedSolutions && (this._relatedSolutions = A(this._deployedSolutions.cards, this._allCards)));
      const c = this._assistantSolutionIds.size > 0 ? i.filter((s) => this._assistantSolutionIds.has(s.deployCommonId)) : i;
      return this.cardsFetched.emit(c.length), this._isLoading = !1, c;
    } else
      return this._isLoading = !1, [];
  }
  async _loadUpdateProcedures() {
    if (this._isDisconnectedEnvironment) {
      this._isLoading = !1;
      return;
    }
    this._isLoading = !0;
    const e = this._configContextConsumer.value;
    this._cardsFetcher = new p(e.locale, e.orgUrl, e.portalURL), this._cardsFetcherDeployed = new p(e.locale, e.orgUrl, e.portalURL), await this._getDeployedSolutions(), this._cards = await this._getSolutions(), this.allCardsFetched.emit(this._cards), this._isLoading = !1;
  }
  async _getDeployedSolutions() {
    const e = this._configContextConsumer.value.authentication, t = this._configContextConsumer.value.userSession;
    if (e && t && e.IsSignedIn) {
      this._abortControllerDeployed ? (this._abortControllerDeployed.abort(), this._abortControllerDeployed = new AbortController()) : this._abortControllerDeployed = new AbortController();
      const i = await E(e, t, this._cardsFetcher, this._cardsFetcherDeployed, x, "created", this._sortOrder, void 0, this._categories, void 0, this._abortControllerDeployed.signal);
      if (this._abortControllerDeployed = void 0, i) {
        if (this._modifiedCheckTry > 0) {
          if (this._deployedSolutions?.cards.length === i?.cards.length)
            return this._modifiedCheckTry--, await this._getDeployedSolutions();
          this._modifiedCheckTry = 0;
        }
        this._deployedSolutions = i;
      }
    }
  }
  _getMeridianSearch() {
    return d`<div><svg aria-hidden=true viewBox="0 0 64 64" width=140 height=140 xmlns=http://www.w3.org/2000/svg fill=var(--calcite-color-text-3)>${C`<path d="M60.217 54.937l-15.77-15.77-1.414 1.415-3.801-3.8a19.94 19.94 0 1 0-2.451 2.45l3.802 3.802-1.413 1.415 15.767 15.767a1.739 1.739 0 0 0 2.459 0l2.82-2.821a1.742 1.742 0 0 0 0-2.458zM4.9 24A19.1 19.1 0 1 1 24 43.1 19.121 19.121 0 0 1 4.9 24zm32.474 14.693q.69-.63 1.32-1.32l3.774 3.775-1.32 1.32zM59.65 56.83l-2.82 2.82a.97.97 0 0 1-1.327 0L40.3 44.45l4.145-4.15L59.65 55.501a.939.939 0 0 1 0 1.328zM22.343 9.62l.097.795q-.31.038-.619.086a13.635 13.635 0 0 0-11.353 11.775l-.026.217-.795-.084.026-.228a14.44 14.44 0 0 1 12.022-12.47c.215-.034.431-.064.648-.09z" />`}</svg></div>`;
  }
  _textSearch(e) {
    this._agoTerms = this._baseAgoTerms + ` ${e}`;
  }
  _sortCards(e) {
    const t = e.sortType;
    this._getSuggested = !1, this._sortOrder = "desc", t === "suggested" ? this._getSuggested = !0 : t === "new" ? this._sortField = "relevance" : t === "relevance" || t === "title" ? (t === "title" && (this._sortOrder = "asc"), this._sortField = t) : t === "updated" && (this._sortField = "relevance"), this.sortType = t;
  }
  _filterCards(e) {
    this._categories = [], e.forEach((t) => {
      if (t.industry) {
        const i = this._getIndustryValue(t.industry);
        if (t.domain) {
          const c = this._getDomainValue(t.domain);
          this._categories.push(`/Categories/${i}/${c}`);
        } else
          this._categories.push(`/Categories/${i}`);
      }
    });
  }
  _getDomainValue(e) {
    return T[e];
  }
  _getIndustryValue(e) {
    return e === "AEC" ? "AEC" : I[e];
  }
  _clearFilterCategories() {
    this._categories = [];
  }
  _isSolutionDeployed(e) {
    return !!this._deployedSolutions?.cards?.some((t) => t?.typeKeywords?.some((i) => i.includes("solutionid") && i.includes(e)));
  }
  _isLatestVersion(e) {
    const t = this._deployedSolutions?.cards?.filter((i) => i?.typeKeywords?.some((c) => c.includes("solutionid") && c.includes(e.deployCommonId)));
    return !(t && t.length > 0 && t[0].deployVersion !== e.deployVersion);
  }
  _lookupSolutionById(e) {
    const t = this._allCards.filter((i) => i.deployCommonId === e);
    t.length > 0 && this.detailsCardSelected.emit(t[0]);
  }
  async _applyAssistantSolutionMatches(e) {
    const t = Array.isArray(e?.solutionIds) ? e.solutionIds.filter(Boolean) : [];
    if (this._agoTerms = this._baseAgoTerms, this._clearFilterCategories(), this._getSuggested = !1, this._assistantSolutionIds = new Set(t), this._allCards.length === 0) {
      await this._loadUpdateProcedures();
      return;
    }
    this._cards = await this._getSolutions();
  }
}
f("solutions-all-panel", $);
export {
  $ as SolutionsAllPanel
};
