/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { c as f } from "../../chunks/runtime.js";
import { css as u, html as a, svg as y } from "lit";
import { u as g } from "../../chunks/useT9n.js";
import { LitElement as w, createEvent as l, nothing as C } from "@arcgis/lumina";
import { useContextConsumer as x } from "@arcgis/lumina/context";
import { createRef as T, ref as d } from "lit/directives/ref.js";
import { C as c } from "../../chunks/CardsFetcher.js";
import { c as v } from "../../chunks/deployAppContexts.js";
import { B as h, T as n, c as b } from "../../chunks/interfaces.js";
import { g as S } from "../../chunks/cardFetchingUtils.js";
import { o as F, k as D } from "../../chunks/helpers.js";
const E = u`calcite-panel{width:100%;height:100%;--calcite-panel-background-color: var(--calcite-color-surface-3)}.card-group{overflow:hidden;padding:.25rem var(--calcite-spacing-xxs) var(--calcite-spacing-md)}.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)}.display-flex{display:flex}.display-none{display:none}.flex-direction-column{flex-direction:column}h1{font-weight:unset;margin:0;padding:0}solution-deployed-card{width:calc(20% - .75rem)}@container (max-width: 1280px){solution-deployed-card{width:calc(25% - .75rem)}}@container (max-width: 1010px){solution-deployed-card{width:calc(33.333% - .75rem)}}@container (max-width: 740px){solution-deployed-card{width:calc(50% - .75rem)}}@container (max-width: 440px){solution-deployed-card{width:calc(100% - .75rem)}}.margin-top-half{margin-top:.5rem}`, m = 5;
class R extends w {
  constructor() {
    super(), this.sortType = "created", this._cards = [], this._cardsFetching = !1, this._modifiedCheckTry = 0, this._newId = "", this._refs = {}, this._showDeleteCompleteAlert = !1, this._deletedSolutionName = "", this._translations = g({ name: "solutions-deployed-panel", blocking: !0 }), this._agoTerms = h, this._allCards = [], this._baseAgoTerms = h, this._categories = [], this._mainPanelRef = T(), this._panelFixed = !1, this._configContextConsumer = x({
      context: v,
      subscribe: !0,
      callback: async (e) => {
        e && (this._initCardsFetchers(), await this._getDeployedSolutions());
      }
    }), this._delay = !1, this._owner = "My solutions", this._sortField = "created", this._sortOrder = "desc", this.deployedCardsFetched = l(), this.searchTermSet = l(), this.sortTypeSet = l(), this.listenOn(window, "solutionDeleted", (e) => {
      this._modifiedCheckTry = m, this.reload(e.detail.showAlert, e.detail.refreshSolutionsTimeout, e.detail.solutionTitle);
    }), this.listenOn(window, "solutionConfigureDialogClose", (e) => {
      e.detail && this.reload(!1, !1);
    }), this.listenOn(window, "deployProgressEnd", (e) => {
      this._modifiedCheckTry = m, this._refreshAfterDeploy(e.detail);
    }), this.listenOn(window, "sortTypeChanged", (e) => {
      e.detail && e.detail.scope === "deployments" && (this.sortType = e.detail.sortType, this._telemetry?.logEvent({
        category: n.DEPLOYMENTS,
        action: "Sort",
        dimensions: [F(e.detail.sortType)]
      }), this.searchSolutions(e.detail));
    }), this.listenOn(window, "searchChanged", (e) => {
      e.detail && e.detail.scope === "deployments" && (e.detail.logSearchTelemetry && e.detail.option?.searchTerm ? this._telemetry?.logEvent({
        category: n.DEPLOYMENTS,
        action: "Search",
        dimensions: [e.detail.option.searchTerm]
      }) : this.searchSolutions(e.detail.option));
    });
  }
  static {
    this.properties = { sortType: 1, _cards: 16, _cardsFetching: 16, _modifiedCheckTry: 16, _newId: 16, _refs: 16, _showDeleteCompleteAlert: 16, _deletedSolutionName: 16, _translations: 16 };
  }
  static {
    this.styles = E;
  }
  get _telemetry() {
    return this._configContextConsumer.value?.telemetrySession;
  }
  async reload(e = !0, t = !0, s) {
    if (this._initCardsFetchers(), e) {
      const i = s || this._translations.solution;
      D({
        kind: "success",
        icon: "check-circle",
        title: this._translations.deleteComplete.replace("{{solutionName}}", i),
        message: "",
        autoClose: !0,
        autoCloseDuration: "fast"
      });
    }
    t ? setTimeout(() => {
      (async () => {
        try {
          await this._getDeployedSolutions();
        } catch (i) {
          console.error("Error getting deployed solutions:", i);
        }
      })();
    }, 500) : await this._getDeployedSolutions();
  }
  async searchSolutions(e) {
    if (e) {
      if ("searchTerm" in e && this._setSearchTerm(e.searchTerm || ""), "sortType" in e && this._setSortOptions(e), Object.keys(e).indexOf("type") > -1) {
        const t = e;
        this._owner = t.value, this._telemetry?.logEvent({
          category: n.DEPLOYMENTS,
          action: "Filter",
          dimensions: [t.value === "My solutions" ? "My content" : "Organization"]
        });
      }
      if (Object.keys(e).indexOf("filter") > -1) {
        const t = e;
        this._owner = t.filter === b.ORG ? "My organization's solutions" : "My solutions";
      }
    } else
      this._agoTerms = this._baseAgoTerms, this._clearFilterCategories();
    await this._getDeployedSolutions();
  }
  async setSearchOptions(e) {
    e && ("searchTerm" in e && (this._setSearchTerm(e.searchTerm), this.searchTermSet.emit({
      searchTerm: e.searchTerm,
      scope: "deployments"
    })), "sortType" in e && (this._setSortOptions(e), this.sortTypeSet.emit({
      sortType: e.sortType,
      scope: "deployments"
    })));
  }
  updated() {
    this._fixPanelContentWrapperFocus();
  }
  _fixPanelContentWrapperFocus() {
    if (!this._panelFixed && this._mainPanelRef.value) {
      const e = this._mainPanelRef.value;
      e.componentOnReady?.().then(() => {
        if (e.shadowRoot) {
          const t = e.shadowRoot.querySelector(".content-wrapper");
          t && (t.tabIndex = -1, this._panelFixed = !0, this._setupPanelObserver());
        }
      }).catch(() => {
        this._panelFixed = !0;
      });
    }
  }
  _setupPanelObserver() {
    if (this._panelObserver)
      return;
    this._panelObserver = new MutationObserver((t) => {
      t.forEach((s) => {
        if (s.type === "attributes" && s.attributeName === "tabindex") {
          const i = s.target;
          i.classList.contains("content-wrapper") && i.tabIndex === 0 && (i.tabIndex = -1);
        }
      });
    });
    const e = this._mainPanelRef.value;
    if (e?.shadowRoot) {
      const t = e.shadowRoot.querySelector(".content-wrapper");
      t && this._panelObserver.observe(t, { attributes: !0, attributeFilter: ["tabindex"] });
    }
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this._panelObserver?.disconnect();
  }
  render() {
    return this._cardsFetching ? a`<calcite-loader .label=${this._translations.fetchingDeployedSolutions}></calcite-loader>` : this._cards.length ? a`<calcite-panel ${d(this._mainPanelRef)}><calcite-card-group class="card-group" .label=${this._translations.allDeployed}>${this._renderCards()}</calcite-card-group></calcite-panel>` : a`<div class="no-solutions">${this._getSolutionsBriefcase()}<div class="text-center leader-1 warning-text trailer-1 display-flex flex-direction-column"><div>${this._translations.noSolutionsFound}</div><div class="margin-top-half">${this._translations.noSolutionsInstruction}</div></div></div>`;
  }
  _initCardsFetchers() {
    if (this._configContextConsumer.value) {
      const e = this._configContextConsumer.value;
      this._cardsFetcher = new c(e.locale, e.orgUrl, e.portalURL), this._cardsFetcherDeployed = new c(e.locale, e.orgUrl, e.portalURL);
    }
  }
  _renderCards() {
    return this._refs = {}, this._cards.map((e) => a`<solution-deployed-card .card=${e} .deployedDate=${e.created} .description=${e.snippet} .diagramKey=${this._configContextConsumer.value?.diagramKey} .heading=${e.title} id=${e.id ?? C} .itemId=${e.id} .owner=${this._owner === "My solutions" ? "" : e.owner} .thumbnail=${e.thumbnailUrl} ${d(this._handleRefs)}></solution-deployed-card>`);
  }
  _handleRefs(e) {
    e && (this._refs[e.id] = e);
  }
  async _getDeployedSolutions() {
    const e = this._configContextConsumer.value.authentication;
    if (e.IsSignedIn) {
      this._abortController ? (this._abortController.abort("redundant request"), this._abortController = new AbortController()) : this._abortController = new AbortController(), this._cardsFetching = !0;
      try {
        const t = await S(e, this._configContextConsumer.value.userSession, this._cardsFetcher, this._cardsFetcherDeployed, this._agoTerms, this._sortField, this._sortOrder, this._delay, this._categories, this._allCards, this._abortController.signal, this._owner);
        this._abortController = void 0, this._modifiedCheckTry > 0 && (this._cards?.length === t?.cards?.length ? (this._modifiedCheckTry--, this._getDeployedSolutions()) : this._modifiedCheckTry = 0), this._cards = t?.cards ?? [], this.deployedCardsFetched.emit(this._cards.length), this._cardsFetching = !1;
      } catch (t) {
        t.message !== "redundant request" && console.warn(t);
      }
    }
  }
  _getSolutionsBriefcase() {
    return a`<div><svg aria-hidden=true viewBox="0 0 64 64" width=200 height=200 xmlns=http://www.w3.org/2000/svg fill=var(--calcite-color-text-3)>${y`<path d="M10.723 54.9h6.409a7.896 7.896 0 0 0 13.736 0h23.896a4.137 4.137 0 0 0 4.136-4.136l-.004-32.446a3.222 3.222 0 0 0-3.217-3.219l-10.779.064V9.836A3.741 3.741 0 0 0 41.163 6.1H23.837A3.741 3.741 0 0 0 20.1 9.836l.067 5.264-10.8.004A3.275 3.275 0 0 0 6.1 18.37L6.096 26a.893.893 0 0 0 .263.636.907.907 0 0 0 .638.263l5.902-.014.013-5.985 38.781.01a.407.407 0 0 1 .407.407l.008 22.925a2.858 2.858 0 0 1-2.857 2.858H30.868a7.896 7.896 0 0 0-13.736 0H12.9v-5.2a.801.801 0 0 0-.8-.8H6.9a.801.801 0 0 0-.8.8l-.001 8.375a4.59 4.59 0 0 0 1.353 3.27 4.658 4.658 0 0 0 3.27 1.355zM6.9 41.9h5.2v6h5.51l.112-.213a7.098 7.098 0 0 1 12.556 0l.113.213h18.86a3.683 3.683 0 0 0 2.587-1.071 3.635 3.635 0 0 0 1.071-2.587L52.9 21.317a1.208 1.208 0 0 0-1.207-1.207l-38.867-.01a.714.714 0 0 0-.714.712l-.011 5.275-5.106.012.001.4-.1-.499.003-7.628a2.471 2.471 0 0 1 2.468-2.469l10.8-.003a.734.734 0 0 0 .733-.733v-5.33A2.94 2.94 0 0 1 23.837 6.9h17.326A2.94 2.94 0 0 1 44.1 9.836v5.327a.734.734 0 0 0 .733.733l10.846.003a2.421 2.421 0 0 1 2.417 2.419l.004 32.446a3.337 3.337 0 0 1-3.336 3.336H30.39l-.113.213a7.098 7.098 0 0 1-12.556 0l-.113-.213h-6.886a3.85 3.85 0 0 1-2.704-1.12 3.796 3.796 0 0 1-1.12-2.705zm17.1 13a3.9 3.9 0 1 0-3.9-3.9 3.905 3.905 0 0 0 3.9 3.9zm0-7a3.1 3.1 0 1 1-3.1 3.1 3.103 3.103 0 0 1 3.1-3.1zm10-6a7.918 7.918 0 0 0 7.349-5h4.818a.734.734 0 0 0 .733-.733v-4.334a.734.734 0 0 0-.733-.733h-4.818a7.9 7.9 0 0 0-14.698 0H5.833a.734.734 0 0 0-.733.733v4.334a.734.734 0 0 0 .733.733h20.818a7.918 7.918 0 0 0 7.349 5zm-28.167-10h21.378l.095-.266a7.1 7.1 0 0 1 13.388 0l.095.266 5.31-.066.068 4.266h-5.378l-.095.266a7.1 7.1 0 0 1-13.388 0l-.095-.266-21.31.066zM34 37.9a3.9 3.9 0 1 0-3.9-3.9 3.905 3.905 0 0 0 3.9 3.9zm0-7a3.1 3.1 0 1 1-3.1 3.1 3.103 3.103 0 0 1 3.1-3.1zm5.658-20.8H25.342a1.244 1.244 0 0 0-1.242 1.242V15.9h16.8v-4.558a1.244 1.244 0 0 0-1.242-1.242zm.442 5H24.9v-3.758a.443.443 0 0 1 .442-.442h14.316a.443.443 0 0 1 .442.442z" />`}</svg></div>`;
  }
  _setSearchTerm(e) {
    this._agoTerms = this._baseAgoTerms + ` ${e}`;
  }
  _setSortOptions(e) {
    const t = e.sortType;
    t === "relevance" || t === "title" ? (t === "title" && (this._sortOrder = "asc"), this._sortField = t) : (t === "updated" || t === "created") && (this._sortOrder = "desc", this._sortField = t), this.sortType = t;
  }
  _clearFilterCategories() {
    this._categories = [];
  }
  async _refreshAfterDeploy(e) {
    if (e) {
      this._newId = e;
      const t = 10, s = 500;
      for (let r = 0; r < t && (await this._getDeployedSolutions(), !this._cards.some((o) => o.id === e)); r++)
        r < t - 1 && await new Promise((o) => setTimeout(o, s));
      await this.updateComplete;
      const i = 10, p = 100;
      for (let r = 0; r < i; r++) {
        if (this._refs[e]) {
          const o = this._cards.find((_) => _.id === e);
          window.dispatchEvent(new CustomEvent("deployedCardReady", {
            detail: { card: o, cardRef: this._refs[e] }
          })), this._newId = "";
          return;
        }
        await new Promise((o) => setTimeout(o, p)), await this.updateComplete;
      }
      console.warn(`Failed to find ref for newly deployed solution after all retries: ${e}`), window.dispatchEvent(new CustomEvent("deploymentCompletedWithoutNav", {
        detail: { solutionId: e }
      })), this._newId = "";
    }
  }
}
f("solutions-deployed-panel", R);
export {
  R as SolutionsDeployedPanel
};
