/* 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 { ref } from "lit/directives/ref.js";
import { u as useT9n } from "../../chunks/useT9n.js";
import { LitElement, createEvent, nothing } from "@arcgis/lumina";
import { useContextConsumer } from "@arcgis/lumina/context";
import { C as CardsFetcher, g as getDeployedSolutions } from "../../chunks/cardFetchingUtils.js";
import { c as configContext } from "../../chunks/deployAppContexts.js";
import { B as BASE_DEPLOYED_TERMS, x as getUserIsAdmin, T as TELEMETRY_CATEGORY } from "../../chunks/interfaces.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-inline-start: var(--calcite-spacing-base);
  padding-top: var(--calcite-spacing-base);
  padding-bottom: var(--calcite-spacing-md);
}

.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%);
}

.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% - 0.75rem);
}

@media (max-width: 1280px) {
  solution-deployed-card {
    width: calc(25% - 0.75rem);
  }
}

@media (max-width: 1010px) {
  solution-deployed-card {
    width: calc(33.333% - 0.75rem);
  }
}

@media (max-width: 740px) {
  solution-deployed-card {
    width: calc(50% - 0.75rem);
  }
}

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

.margin-top-half {
  margin-top: 0.5rem;
}
`;
const MAX_REQUERY = 5;
class SolutionsDeployedPanel extends LitElement {
  constructor() {
    super();
    this.sortType = "created";
    this._cards = [];
    this._cardsFetching = false;
    this._modifiedCheckTry = 0;
    this._newId = "";
    this._refs = {};
    this._showDeleteCompleteAlert = false;
    this._deletedSolutionName = "";
    this._translations = useT9n({ name: "solutions-deployed-panel", blocking: true });
    this._agoTerms = BASE_DEPLOYED_TERMS;
    this._allCards = [];
    this._baseAgoTerms = BASE_DEPLOYED_TERMS;
    this._categories = [];
    this._configContextConsumer = useContextConsumer({
      context: configContext,
      subscribe: true,
      callback: async (evt) => {
        if (evt) {
          this._initCardsFetchers();
          this._isOrgAdmin = getUserIsAdmin(this._configContextConsumer.value.authentication);
          await this._getDeployedSolutions();
        }
      }
    });
    this._delay = false;
    this._isOrgAdmin = false;
    this._owner = "My solutions";
    this._sortField = "created";
    this._sortOrder = "desc";
    this.deployedCardsFetched = createEvent();
    this.searchTermSet = createEvent();
    this.sortTypeSet = createEvent();
    this.listenOn(window, "solutionDeleted", (value) => {
      this._modifiedCheckTry = MAX_REQUERY;
      this.reload(value.detail.showAlert, value.detail.refreshSolutionsTimeout, value.detail.solutionTitle);
    });
    this.listenOn(window, "solutionConfigureDialogClose", (evt) => {
      if (evt.detail) {
        this.reload(false, false);
      }
    });
    this.listenOn(window, "deployProgressEnd", (evt) => {
      this._modifiedCheckTry = MAX_REQUERY;
      this._refreshAfterDeploy(evt.detail);
    });
    this.listenOn(window, "sortTypeChanged", (evt) => {
      if (evt.detail && evt.detail.scope === "deployments") {
        this.sortType = evt.detail.sortType;
        this._telemetry?.logEvent({
          category: TELEMETRY_CATEGORY.DEPLOYMENTS,
          action: "Sort",
          dimensions: [getSortTypeDisplayName(evt.detail.sortType)]
        });
        this.searchSolutions(evt.detail);
      }
    });
    this.listenOn(window, "searchChanged", (evt) => {
      if (evt.detail && evt.detail.scope === "deployments") {
        if (evt.detail.logSearchTelemetry && evt.detail.option?.searchTerm) {
          this._telemetry?.logEvent({
            category: TELEMETRY_CATEGORY.DEPLOYMENTS,
            action: "Search",
            dimensions: [evt.detail.option.searchTerm]
          });
        } else {
          this.searchSolutions(evt.detail.option);
        }
      }
    });
  }
  static {
    this.properties = { sortType: 1, _cards: [16, {}, { state: true }], _cardsFetching: [16, {}, { state: true }], _modifiedCheckTry: [16, {}, { state: true }], _newId: [16, {}, { state: true }], _refs: [16, {}, { state: true }], _showDeleteCompleteAlert: [16, {}, { state: true }], _deletedSolutionName: [16, {}, { state: true }], _translations: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  get _telemetry() {
    return this._configContextConsumer.value?.telemetrySession;
  }
  async reload(showDeleteMessage = true, useTimeout = true, solutionTitle) {
    this._initCardsFetchers();
    if (showDeleteMessage) {
      this._showDeleteCompleteAlert = true;
      this._deletedSolutionName = solutionTitle || this._translations.solution;
    }
    if (useTimeout) {
      setTimeout(() => {
        void (async () => {
          try {
            await this._getDeployedSolutions();
          } catch (err) {
            console.error("Error getting deployed solutions:", err);
          }
        })();
      }, 500);
    } else {
      await this._getDeployedSolutions();
    }
  }
  async searchSolutions(searchOptions) {
    if (searchOptions) {
      if ("searchTerm" in searchOptions) {
        this._textSearch(searchOptions.searchTerm);
      } else if ("sortType" in searchOptions) {
        this._sortCards(searchOptions);
      } else {
        if (searchOptions.type === "owner") {
          this._owner = searchOptions.value;
          this._telemetry?.logEvent({
            category: TELEMETRY_CATEGORY.DEPLOYMENTS,
            action: "Filter",
            dimensions: [searchOptions.value === "My solutions" ? "My content" : "Organization"]
          });
        }
      }
    } else {
      this._agoTerms = this._baseAgoTerms;
      this._clearFilterCategories();
    }
    await this._getDeployedSolutions();
  }
  async setSearchOptions(searchOptions) {
    if (searchOptions) {
      if ("searchTerm" in searchOptions) {
        this._textSearch(searchOptions.searchTerm);
        this.searchTermSet.emit({
          searchTerm: searchOptions.searchTerm,
          scope: "deployments"
        });
      }
      if ("sortType" in searchOptions) {
        this._sortCards(searchOptions);
        this.sortTypeSet.emit({
          sortType: searchOptions.sortType,
          scope: "deployments"
        });
      }
    }
  }
  render() {
    if (this._cardsFetching) {
      return html`<calcite-loader .label=${this._translations.fetchingDeployedSolutions}></calcite-loader>`;
    }
    if (!this._cards.length) {
      return html`<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>`;
    }
    return html`<calcite-panel><calcite-card-group class="card-group" .label=${this._translations.allDeployed}>${this._renderCards()}</calcite-card-group><calcite-alert auto-close auto-close-duration=fast icon=check-circle kind=success .label=${this._translations.deleteComplete.replace("{{solutionName}}", this._deletedSolutionName)} .open=${this._showDeleteCompleteAlert} @calciteAlertClose=${() => {
      this._showDeleteCompleteAlert = false;
    }}><div slot=title>${this._translations.deleteComplete.replace("{{solutionName}}", this._deletedSolutionName)}</div></calcite-alert></calcite-panel>`;
  }
  _initCardsFetchers() {
    if (this._configContextConsumer.value) {
      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);
    }
  }
  _renderCards() {
    this._refs = {};
    return this._cards.map((card) => html`<solution-deployed-card .allowDelete=${this._isOrgAdmin || card.owner === this._configContextConsumer.value.userSession.username || this.checkDeletePermissions()} .card=${card} .deployedDate=${card.created} .description=${card.snippet} .diagramKey=${this._configContextConsumer.value?.diagramKey} .heading=${card.title} id=${card.id ?? nothing} .itemId=${card.id} .owner=${this._owner === "My solutions" ? "" : card.owner} .thumbnail=${card.thumbnailUrl} ${ref(this._handleRefs)}></solution-deployed-card>`);
  }
  _handleRefs(el) {
    if (el) {
      this._refs[el.id] = el;
    }
  }
  async _getDeployedSolutions() {
    const auth = this._configContextConsumer.value.authentication;
    if (auth.IsSignedIn) {
      this._cardsFetching = true;
      const deployedSolutions = await getDeployedSolutions(auth, this._configContextConsumer.value.userSession, this._cardsFetcher, this._cardsFetcherDeployed, this._agoTerms, this._sortField, this._sortOrder, this._delay, this._categories, this._allCards, this._owner);
      if (this._modifiedCheckTry > 0) {
        if (this._cards.length === deployedSolutions?.cards.length) {
          this._modifiedCheckTry--;
          this._getDeployedSolutions();
        } else {
          this._modifiedCheckTry = 0;
        }
      }
      this._cards = deployedSolutions?.cards ?? [];
      this.deployedCardsFetched.emit(this._cards.length);
      this._cardsFetching = false;
    }
  }
  _getSolutionsBriefcase() {
    return html`<div class="solutions-briefcase"><svg viewBox="0 0 64 64" width=200 height=200 xmlns=http://www.w3.org/2000/svg fill=var(--calcite-color-text-3)>${svg`<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>`;
  }
  _textSearch(searchText) {
    this._agoTerms = this._baseAgoTerms + ` ${searchText}`;
  }
  _sortCards(sortOption) {
    const sortType = sortOption.sortType;
    if (sortType === "relevance" || sortType === "title") {
      if (sortType === "title") {
        this._sortOrder = "asc";
      }
      this._sortField = sortType;
    } else if (sortType === "updated" || sortType === "created") {
      this._sortOrder = "desc";
      this._sortField = sortType;
    }
    this.sortType = sortType;
  }
  _clearFilterCategories() {
    this._categories = [];
  }
  checkDeletePermissions() {
    const userInfo = this._configContextConsumer.value.authentication;
    if (userInfo?.PortalUserPrivileges && userInfo.PortalUserPrivileges.length > 0) {
      return userInfo.PortalUserPrivileges.some((priviledge) => priviledge === "portal:admin:deleteItems");
    }
    return false;
  }
  async _refreshAfterDeploy(newSolutionId) {
    if (newSolutionId) {
      this._newId = newSolutionId;
      const maxCardRetries = 10;
      const cardRetryDelay = 500;
      for (let i = 0; i < maxCardRetries; i++) {
        await this._getDeployedSolutions();
        if (this._cards.some((c) => c.id === newSolutionId)) {
          break;
        }
        if (i < maxCardRetries - 1) {
          await new Promise((resolve) => setTimeout(resolve, cardRetryDelay));
        }
      }
      await this.updateComplete;
      const maxRefRetries = 10;
      const refRetryDelay = 100;
      for (let i = 0; i < maxRefRetries; i++) {
        if (this._refs[newSolutionId]) {
          const card = this._cards.find((c) => c.id === newSolutionId);
          window.dispatchEvent(new CustomEvent("deployedCardReady", {
            detail: { card, cardRef: this._refs[newSolutionId] }
          }));
          this._newId = "";
          return;
        }
        await new Promise((resolve) => setTimeout(resolve, refRetryDelay));
        await this.updateComplete;
      }
      console.error(`Failed to find ref for newly deployed solution: ${newSolutionId}`);
      this._newId = "";
    }
  }
}
customElement("solutions-deployed-panel", SolutionsDeployedPanel);
export {
  SolutionsDeployedPanel
};
