/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { c as customElement } from "../../chunks/runtime.js";
import { css, html, svg } from "lit";
import { u as useT9n } from "../../chunks/useT9n.js";
import { LitElement, createEvent } from "@arcgis/lumina";
import { useContextConsumer } from "@arcgis/lumina/context";
import { a as BASE_SOLUTIONS_TERMS, T as TELEMETRY_CATEGORY, c as EDomain, d as EIndustry, B as BASE_DEPLOYED_TERMS } from "../../chunks/interfaces.js";
import { C as CardsFetcher, g as getDeployedSolutions } from "../../chunks/cardFetchingUtils.js";
import { b as getDeployedRelatedSolutionIds } from "../../chunks/cardsHelpers.js";
import { c as configContext } from "../../chunks/deployAppContexts.js";
import { c as getSortTypeDisplayName } from "../../chunks/helpers.js";
const styles = css`/** @license
 * Copyright 2025 Esri
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

calcite-panel {
  width: 100%;
  height: 100%;
  --calcite-panel-background-color: var(--calcite-color-foreground-2);
}

.card-group {
  overflow: hidden;
  padding: 0.2rem var(--calcite-spacing-md) var(--calcite-spacing-md);
}

solution-details-card{
  width: calc(25% - 0.6rem);
}

@media (max-width: 1234px) {
  solution-details-card {
    width: calc(33.333% - 0.6rem);
  }
}

@media (max-width: 1010px) {
  solution-details-card {
    width: calc(50% - 0.6rem);
  }
}

/* We go back to 3 cards below 800 because the filter tree on the left disappears */
/* See the solutions-all-shell.css for the filter disappearing selector */
@media (max-width: 800px) {
  solution-details-card {
    width: calc(33.33% - 0.6rem);
  }
}

@media (max-width: 680px) {
  solution-details-card {
    width: calc(50% - 0.6rem);
  }
}

@media (max-width: 440px) {
  solution-details-card {
    width: calc(100% - 0.75rem);
  }
}

.solutions-briefcase {
  margin: auto;
  padding-top: var(--calcite-spacing-xxxl);
}

.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;
  width: 100%;
  height: 100%;
  transform: translateY(50%);
}

.margin-top-half {
  margin-top: 0.5rem;
}

.margin-top-1 {
  margin-top: 1rem;
}

.no-solutions-prompt {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
}
`;
const MAX_REQUERY = 5;
class SolutionsAllPanel extends LitElement {
  constructor() {
    super();
    this.sortType = "relevance";
    this._cards = [];
    this._isLoading = true;
    this._modifiedCheckTry = 0;
    this._translations = useT9n({ name: "solutions-all-panel", blocking: true });
    this._agoTerms = `${BASE_SOLUTIONS_TERMS}`;
    this._allCards = [];
    this._baseAgoTerms = BASE_SOLUTIONS_TERMS;
    this._categories = [];
    this._configContextConsumer = useContextConsumer({
      context: configContext,
      subscribe: true,
      callback: async (evt) => {
        if (evt) {
          await this._loadUpdateProcedures();
        }
      }
    });
    this._delay = false;
    this._getSuggested = false;
    this._relatedSolutions = /* @__PURE__ */ new Set();
    this._sortField = "relevance";
    this._sortOrder = "desc";
    this.cardsFetched = createEvent();
    this.allCardsFetched = createEvent();
    this.searchTermSet = createEvent();
    this.sortTypeSet = createEvent();
    this.detailsCardSelected = createEvent();
    this._handleOpenAssistant = () => {
      this._telemetry?.logEvent({
        category: TELEMETRY_CATEGORY.ASSISTANT,
        action: "Open"
      });
      window.dispatchEvent(new CustomEvent("openAssistant"));
    };
    this.listenOn(window, "deployProgressEnd", () => {
      this._modifiedCheckTry = MAX_REQUERY;
      this._loadUpdateProcedures();
    });
    this.listenOn(window, "solutionDeleted", () => {
      this._modifiedCheckTry = MAX_REQUERY;
      this._loadUpdateProcedures();
    });
    this.listenOn(window, "sortTypeChanged", (evt) => {
      if (evt.detail && evt.detail.scope === "all-solutions") {
        this.sortType = evt.detail.sortType;
        this._telemetry?.logEvent({
          category: TELEMETRY_CATEGORY.ALL_SOLUTIONS,
          action: "Sort",
          dimensions: [getSortTypeDisplayName(evt.detail.sortType)]
        });
        if (this.sortType === "suggested" && this._deployedSolutions?.cards.length === 0) {
          this._getDeployedSolutions().then(() => {
            this.searchSolutions(evt.detail);
          });
        } else {
          this.searchSolutions(evt.detail);
        }
      }
    });
    this.listenOn(window, "solutionIDFromAssistant", (id) => {
      this._lookupSolutionById(id.detail);
    });
  }
  static {
    this.properties = { sortType: 1, _cards: [16, {}, { state: true }], _isLoading: [16, {}, { state: true }], _modifiedCheckTry: [16, {}, { state: true }], _translations: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  get _telemetry() {
    return this._configContextConsumer.value?.telemetrySession;
  }
  async searchSolutions(searchOptions) {
    if (searchOptions) {
      if ("searchTerm" in searchOptions) {
        this._textSearch(searchOptions.searchTerm);
      } else if ("sortType" in searchOptions) {
        this._sortCards(searchOptions);
      } else {
        this._filterCards(searchOptions);
      }
    } else {
      this._agoTerms = this._baseAgoTerms;
      this._clearFilterCategories();
    }
    this._cards = await this._getSolutions();
  }
  async setSearchOptions(searchOptions) {
    if (searchOptions) {
      if ("searchTerm" in searchOptions) {
        this._textSearch(searchOptions.searchTerm);
        this.searchTermSet.emit({
          searchTerm: searchOptions.searchTerm,
          scope: "all-solutions"
        });
      }
      if ("sortType" in searchOptions) {
        this._sortCards(searchOptions);
        this.sortTypeSet.emit({
          sortType: searchOptions.sortType,
          scope: "all-solutions"
        });
      }
    }
  }
  render() {
    const canUseAssistant = this._configContextConsumer.value?.authentication?.IsSignedIn && this._configContextConsumer.value?.authentication?.CanUseAI;
    return this._isLoading || this._cards.length ? html`<calcite-panel>${this._isLoading ? html`<calcite-loader id=solutions-all-panel-loader .label=${this._translations.fetchingSolutions}></calcite-loader>` : html`<calcite-card-group class="card-group" .label=${this._translations.allSolutionCards}>${this._renderCards()}</calcite-card-group>`}</calcite-panel>` : html`<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">${canUseAssistant ? this._translations.assistantHelp : this._translations.changeSearchTerm}</div></div>${canUseAssistant && html`<calcite-button appearance=outline icon-start=speech-bubbles @click=${this._handleOpenAssistant} scale=l>${this._translations.askAssistant}</calcite-button>` || ""}</div></div>`;
  }
  _renderCards() {
    return this._cards.map((card) => {
      return html`<solution-details-card .card=${card}></solution-details-card>`;
    });
  }
  async _getSolutions() {
    if (this._configContextConsumer.value) {
      this._isLoading = true;
      const fetchedCards = 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
      }, this._configContextConsumer.value?.primarySolutionsGroupId, this._configContextConsumer.value?.agoBasedEnterpriseSolutionsGroupId, this._configContextConsumer.value?.userSession, this._configContextConsumer.value?.isEnterprise, {
        "num": 1e3
      });
      const cards = fetchedCards?.cards.length ? fetchedCards.cards : [];
      if (this.sortType === "new" || this.sortType === "updated") {
        let releaseType = "/Categories/New Release";
        if (this.sortType === "updated") {
          releaseType = "/Categories/Updated";
        }
        cards.sort((a, b) => {
          if (a.categories.includes(releaseType) && !b.categories.includes(releaseType)) {
            return -1;
          } else if (!a.categories.includes(releaseType) && b.categories.includes(releaseType)) {
            return 1;
          } else if (a.categories.includes(releaseType) && b.categories.includes(releaseType)) {
            return a.categories.length - b.categories.length;
          } else {
            return 0;
          }
        });
      } else if (this.sortType === "suggested") {
        if (this._relatedSolutions.size > 0 && this._deployedSolutions?.cards?.length) {
          const cardVersionMap = /* @__PURE__ */ new Map();
          for (const c of cards) {
            const existing = cardVersionMap.get(c.deployCommonId);
            const version = Number(c.deployVersion);
            if (!existing || version > existing) {
              cardVersionMap.set(c.deployCommonId, version);
            }
          }
          const deployedMatches = this._deployedSolutions.cards.filter((d) => {
            const cardVersion = cardVersionMap.get(d.deployCommonId);
            return cardVersion !== void 0 && Number(d.deployVersion) >= cardVersion;
          });
          const deployedIds = new Set(deployedMatches.map((d) => d.deployCommonId));
          this._relatedSolutions = new Set([...this._relatedSolutions].filter((id) => !deployedIds.has(id)));
          cards.sort((a, b) => {
            const inRelatedA = this._relatedSolutions.has(a.deployCommonId);
            const inRelatedB = this._relatedSolutions.has(b.deployCommonId);
            if (inRelatedA && !inRelatedB)
              return -1;
            if (!inRelatedA && inRelatedB)
              return 1;
            return 0;
          });
        }
      }
      const solutionDetailsCards = cards.map((fetchedCard) => {
        const hasNewRelease = fetchedCard.categories.indexOf("/Categories/New Release") > -1;
        const hasUpdatedRelease = fetchedCard.categories.indexOf("/Categories/Updated") > -1;
        let isDeployed = false;
        let isLatestVersion = true;
        if (this._deployedSolutions) {
          isDeployed = this._isSolutionDeployed(fetchedCard.deployCommonId);
          isLatestVersion = this._isLatestVersion(fetchedCard);
        }
        const chips = [];
        if (hasNewRelease) {
          chips.push("new");
        } else if (hasUpdatedRelease) {
          chips.push("updated");
        }
        if (isDeployed && isLatestVersion) {
          chips.push("deployed");
        }
        fetchedCard.chips = chips.length > 0 ? chips : void 0;
        fetchedCard.supportReuse = isDeployed ? isDeployed && !isLatestVersion ? true : false : true;
        return fetchedCard;
      });
      if (this._allCards.length === 0 && fetchedCards?.cards) {
        this._allCards = fetchedCards?.cards;
        if (this._deployedSolutions) {
          this._relatedSolutions = getDeployedRelatedSolutionIds(this._deployedSolutions.cards, this._allCards);
        }
      }
      this.cardsFetched.emit(solutionDetailsCards.length);
      this._isLoading = false;
      return solutionDetailsCards;
    } else {
      this._isLoading = false;
      return [];
    }
  }
  async _loadUpdateProcedures() {
    this._isLoading = true;
    const config = this._configContextConsumer.value;
    this._cardsFetcher = new CardsFetcher(config.locale, config.orgUrl, config.portalURL);
    this._cardsFetcherDeployed = new CardsFetcher(config.locale, config.orgUrl, config.portalURL);
    await this._getDeployedSolutions();
    this._cards = await this._getSolutions();
    this.allCardsFetched.emit(this._cards);
    this._isLoading = false;
  }
  async _getDeployedSolutions() {
    const authentication = this._configContextConsumer.value.authentication;
    const userSession = this._configContextConsumer.value.userSession;
    if (authentication && userSession && authentication.IsSignedIn) {
      const deployedSolutions = await getDeployedSolutions(authentication, userSession, this._cardsFetcher, this._cardsFetcherDeployed, BASE_DEPLOYED_TERMS, "created");
      if (deployedSolutions) {
        if (this._modifiedCheckTry > 0) {
          if (this._deployedSolutions?.cards.length === deployedSolutions?.cards.length) {
            this._modifiedCheckTry--;
            return await this._getDeployedSolutions();
          } else {
            this._modifiedCheckTry = 0;
          }
        }
        this._deployedSolutions = deployedSolutions;
      }
    }
  }
  _getMeridianSearch() {
    return html`<div class="solutions-briefcase"><svg viewBox="0 0 64 64" width=140 height=140 xmlns=http://www.w3.org/2000/svg fill=var(--calcite-color-text-3)>${svg`<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(searchText) {
    this._agoTerms = this._baseAgoTerms + ` ${searchText}`;
  }
  _sortCards(sortOption) {
    const sortType = sortOption.sortType;
    this._getSuggested = false;
    this._sortOrder = "desc";
    if (sortType === "suggested") {
      this._getSuggested = true;
    } else if (sortType === "new") {
      this._sortField = "relevance";
    } else if (sortType === "relevance" || sortType === "title") {
      if (sortType === "title") {
        this._sortOrder = "asc";
      }
      this._sortField = sortType;
    } else if (sortType === "updated") {
      this._sortField = "relevance";
    }
    this.sortType = sortType;
  }
  _filterCards(filterOptions) {
    this._categories = [];
    filterOptions.forEach((filterOption) => {
      if (filterOption.industry) {
        const industry = this._getIndustryValue(filterOption.industry);
        if (filterOption.domain) {
          const domain = this._getDomainValue(filterOption.domain);
          this._categories.push(`/Categories/${industry}/${domain}`);
        } else {
          this._categories.push(`/Categories/${industry}`);
        }
      }
    });
  }
  _getDomainValue(key) {
    return EDomain[key];
  }
  _getIndustryValue(key) {
    return key === "AEC" ? "AEC" : EIndustry[key];
  }
  _clearFilterCategories() {
    this._categories = [];
  }
  _isSolutionDeployed(solutionId) {
    return !!this._deployedSolutions?.cards?.some((card) => card?.typeKeywords?.some((k) => k.includes("solutionid") && k.includes(solutionId)));
  }
  _isLatestVersion(solutionCard) {
    const matchCards = this._deployedSolutions?.cards?.filter((card) => card?.typeKeywords?.some((k) => k.includes("solutionid") && k.includes(solutionCard.deployCommonId)));
    if (matchCards && matchCards.length > 0) {
      const matchCard = matchCards[0];
      if (matchCard.deployVersion !== solutionCard.deployVersion) {
        return false;
      }
    }
    return true;
  }
  _lookupSolutionById(id) {
    const foundItem = this._cards.filter((card) => {
      const justKeywords = card.typeKeywords;
      return justKeywords.includes(id);
    });
    if (foundItem.length > 0) {
      this.detailsCardSelected.emit(foundItem[0]);
    }
  }
}
customElement("solutions-all-panel", SolutionsAllPanel);
export {
  SolutionsAllPanel
};
