/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { c as customElement } from "../../chunks/runtime.js";
import { css, html } from "lit";
import { keyed } from "lit/directives/keyed.js";
import { ref } from "lit/directives/ref.js";
import { u as useT9n } from "../../chunks/useT9n.js";
import { LitElement, createEvent, safeClassMap, nothing } from "@arcgis/lumina";
import { useContextConsumer } from "@arcgis/lumina/context";
import { c as configContext } from "../../chunks/deployAppContexts.js";
import { x as getUserIsAdmin, T as TELEMETRY_CATEGORY, w as prepareDataForSolutionDisplay } from "../../chunks/interfaces.js";
import { f as findSolutionByTypeKeywordSolutionId, g as getSolutionVersionFromTypekeyword, a as findSolutionTitleByDeployCommonId } from "../../chunks/cardsHelpers.js";
import { g as getRelatedSolutionsInfos } from "../../chunks/getRelatedInfos.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.
 */

.font-weight-med {
  font-weight: var(--calcite-font-weight-medium);
}

.font-weight-bold {
  font-weight: var(--calcite-font-weight-bold);
}

.heading-font {
  font-size: var(--calcite-font-size-0);
  font-weight: var(--calcite-font-weight-medium);
}

.title-font {
  font-size: 1.8rem;
  font-weight: var(--calcite-font-weight-medium);
  color: var(--calcite-color-text-1);
}

.font-1 {
  font-size: var(--calcite-spacing-lg);
}

.display-flex {
  display: flex;
}

.display-none {
  display: none;
}

.flex-direction-column {
  flex-direction: column;
}

.flex-direction-row {
  flex-direction: row;
}

.icon-color {
  color: var(--calcite-color-text-3);
}

.padding-end-xxl {
  padding-inline-end: var(--calcite-spacing-xxl);
}

.padding-bottom-lg {
  padding-bottom: var(--calcite-spacing-lg);
}

.padding-bottom-xxl {
  padding-bottom: var(--calcite-spacing-xxl);
}

.item-padding {
  --calcite-internal-accordion-item-padding: var(--calcite-spacing-xl);
}

.align-items-center {
  align-items: center;
}

.align-items-start {
  align-items: start;
}

.font-size-override {
  --calcite-font-size--2: var(--calcite-font-size--1);
}

.background-color-2 {
  background-color: var(--calcite-color-foreground-2);
}

.label-override {
  --calcite-label-margin-bottom: var(--calcite-spacing-none);
}

.position-relative {
  position: relative;
}

.overflow-hidden {
  overflow: hidden;
}

.overflow-auto {
  overflow: auto;
}

.margin-block-start-end-0 {
  margin-block-start: var(--calcite-spacing-none);
  margin-block-end: var(--calcite-spacing-none);
}

.panel-background-2 {
  --calcite-panel-background-color: var(--calcite-color-foreground-2);
  background-color: var(--calcite-color-foreground-2);
}

.panel-background-1 {
  --calcite-panel-background-color: var(--calcite-color-foreground-1);
  --calcite-shell-panel-background-color: var(--calcite-color-foreground-1);
}

.border-none {
  border: none;
}

.font-color-1 {
  color: var(--calcite-color-text-1);
}

.panel-bg-color {
  --calcite-panel-header-background-color: var(--calcite-color-foreground-1);
  --calcite-panel-background-color: var(--calcite-color-foreground-1);
}

.dialog-y-size {
  --calcite-dialog-size-y: 90%
}

.dialog-x-size {
  --calcite-dialog-size-x: 90%
}

.bottom-border {
  border-bottom: solid var(--calcite-spacing-px);
  color: var(--calcite-color-border-1);
}

.margin-start-end-xxl {
  margin-inline-start: var(--calcite-spacing-xxl);
  margin-inline-end: var(--calcite-spacing-xxl);
}

.justify-between {
  justify-content: space-between;
}

.items-baseline {
  align-items: baseline;
}

.padding-xxl {
  padding: var(--calcite-spacing-xxl);
}

.padding-top-xxl {
  padding-top: var(--calcite-spacing-xxl);
}

.padding-top-lg {
  padding-top: var(--calcite-spacing-lg);
}

.padding-bottom-xxl {
  padding-bottom: var(--calcite-spacing-xxl);
}

.padding-end-1 {
  padding-inline-end: var(--calcite-spacing-lg);
}

.padding-end-xxl {
  padding-inline-end: var(--calcite-spacing-xxl);
}

.padding-start-sm {
  padding-inline-start: var(--calcite-spacing-sm);
}

.padding-start-xxl {
  padding-inline-start: var(--calcite-spacing-xxl);
}

.image-width {
  width: 300px;
  flex-grow: 0;
  flex-shrink: 0;
}

@media (max-width: 1280px) {
  .image-width {
    flex-grow: 2;
    flex-shrink: 0.5;
  }
}

img {
  max-width: 100%;
  height: auto;
  overflow-clip-margin: content-box;
  overflow: clip;
  display: block;
}

.margin-xl {
  margin: var(--calcite-spacing-xl);
}

.line-height-1 {
  line-height: 1.1;
}

.line-height-xxl {
  line-height: var(--calcite-line-height-xxl);
}

@media (max-width: 800px) {
  .image-width {
    display: none;
  }
}

calcite-shell-panel {
  --calcite-shell-panel-max-width: 20rem;
  --calcite-shell-panel-width: 24vw;
}

calcite-shell {
  block-size: unset;
}
`;
class SolutionDeployedCardPanel extends LitElement {
  constructor() {
    super();
    this.diagramKey = "";
    this.open = false;
    this.templateInfos = [];
    this._accordionLoading = false;
    this._configureTitlesOpen = false;
    this._deleteDialogOpen = false;
    this._hasNewVersion = false;
    this._isDiagramOpen = false;
    this._isNameConflict = false;
    this._invalidNameMessage = "";
    this._showSuccessAlert = false;
    this._showFailedAlert = false;
    this._showItemUpdateLoading = false;
    this._templateInfoGraph = [];
    this._translations = useT9n({ name: "solution-deployed-card-panel", blocking: true });
    this._configContextConsumer = useContextConsumer({
      context: configContext,
      subscribe: true,
      callback: async (evt) => {
        if (evt) {
          this._isOrgAdmin = evt.authentication?.PortalUserSubset?.role === "org_admin" || getUserIsAdmin(evt.authentication);
          this._user = evt.authentication?.Portal?.user;
        }
      }
    });
    this._isOrgAdmin = false;
    this.navTabSelected = createEvent();
    this.sortTypeChanged = createEvent();
    this.solutionConfigureDialogClose = createEvent();
    this._nonSolutionDependencyItems = [];
    this.listenOn(window, "deployedCardSelected", this._deployedCardSelected);
    this.listenOn(window, "deployAppTabSelected", this._handleDeployAppTabSelected);
    this.listenOn(window, "displayDeployedCard", () => {
      this._showSuccessAlert = true;
    });
  }
  static {
    this.properties = { card: [0, {}, { attribute: false }], cardRef: 1, diagramKey: 1, open: [5, {}, { type: Boolean }], templateInfos: [0, {}, { attribute: false }], _accordionLoading: [16, {}, { state: true }], _configureTitlesOpen: [16, {}, { state: true }], _deleteDialogOpen: [16, {}, { state: true }], _hasNewVersion: [16, {}, { state: true }], _isDiagramOpen: [16, {}, { state: true }], _isNameConflict: [16, {}, { state: true }], _invalidNameMessage: [16, {}, { state: true }], _showSuccessAlert: [16, {}, { state: true }], _showFailedAlert: [16, {}, { state: true }], _showItemUpdateLoading: [16, {}, { state: true }], _templateInfoGraph: [16, {}, { state: true }], _translations: [16, {}, { state: true }], _nonSolutionDependencyItems: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  get _telemetry() {
    return this._configContextConsumer.value?.telemetrySession;
  }
  render() {
    return html`<calcite-shell class="position-relative background-color-2"><calcite-panel class="padding-end-xxl panel-background-2 border-none" slot=panel-bottom><div class="display-flex flex-direction-column overflow-hidden"><div class="background-color-2 padding-top-xxl">${this._getSolutionPanel()}</div>${this._getSolutionContents()}</div></calcite-panel><calcite-shell-panel class="panel-background-1" slot=panel-end>${this._getButtons()}${this._getOwnerSection()}<div class="bottom-border margin-start-end-xxl"></div>${this._getSolutionVersionCard()}</calcite-shell-panel>${this._renderDiagramDialog()}${this._getConfigureTitlesDialog()}${this._getDeleteDialog()}${this._getSuccessDeployAlert()}</calcite-shell>`;
  }
  async _deployedCardSelected(evt) {
    const deployedCard = evt.detail;
    this.card = deployedCard.card;
    this.cardRef = deployedCard.cardRef;
    this.templateInfos = [];
    this._accordionLoading = true;
    this.templateInfos = await this._getTemplates();
    this._accordionLoading = false;
    const relatedInfos = await getRelatedSolutionsInfos(this._configContextConsumer.value.userSession, this.card);
    this._nonSolutionDependencyItems = relatedInfos._nonSolutionDependencyItems;
    setTimeout(async () => {
      await this._accordionRef.expandFirstItem();
      if (relatedInfos.uniqueIitemIds.length > 0) {
        this._accordionRef.listSelectionMode = "multiple";
        this._accordionRef.selectItems(relatedInfos.uniqueIitemIds);
      }
    }, 250);
    const sourceSolutionCard = findSolutionByTypeKeywordSolutionId(this._configContextConsumer.value?.allCards || [], this.card.deployCommonId);
    let hasNewVersion = false;
    if (sourceSolutionCard) {
      const sourceVersion = getSolutionVersionFromTypekeyword(sourceSolutionCard);
      const deployedVersion = getSolutionVersionFromTypekeyword(this.card);
      hasNewVersion = sourceVersion > deployedVersion;
    }
    this._hasNewVersion = hasNewVersion;
  }
  _handleDeployAppTabSelected(evt) {
    const activeTab = evt.detail;
    if (activeTab === "deployed-card") {
      this.sortTypeChanged.emit("");
    }
  }
  _getButtons() {
    const userName = this._configContextConsumer.value?.userSession?.username;
    const canEditTitles = this.card?.owner === userName || this._isOrgAdmin;
    const editTitlesTooltipClass = canEditTitles ? "display-none" : "";
    return html`<div class="display-flex flex-direction-column padding-xxl"><calcite-button appearance=outline class="padding-bottom-lg" kind=neutral @click=${this._openDiagram}>${this._translations.viewTheDiagram}</calcite-button><calcite-button appearance=outline class="padding-bottom-lg" kind=neutral @click=${this._viewDocumentation}>${this._translations.solutionDocumentation}</calcite-button><calcite-button appearance=outline class="padding-bottom-lg" kind=neutral @click=${this._openItemDetails}>${this._translations.itemDetails}</calcite-button><calcite-button appearance=outline class="padding-bottom-lg" .disabled=${!canEditTitles} id=solution-configure-titles-button kind=neutral @click=${this._openConfigureTitlesDialog}>${this._translations.updateTitles}</calcite-button><calcite-tooltip class=${safeClassMap(editTitlesTooltipClass)} overlay-positioning=fixed reference-element=solution-configure-titles-button><span>${this._translations.mustOwnSolution}</span></calcite-tooltip><calcite-button appearance=outline class="padding-bottom-lg" kind=neutral @click=${this._deleteSolution}>${this._translations.deleteSolution}</calcite-button></div>`;
  }
  _openConfigureTitlesDialog() {
    this._configureTitlesOpen = true;
  }
  _getConfigureTitlesDialog() {
    return this._configureTitlesOpen ? html`<solution-configure-titles .card=${this.card} @solutionConfigureTitlesBeforeClose=${async () => {
      this.templateInfos = await this._getTemplates();
      this._configureTitlesOpen = false;
    }} @solutionItemsTitlesChanged=${async () => {
      this.templateInfos = await this._getTemplates();
    }} .open=${this._configureTitlesOpen} source="Details Page" .templateInfos=${this.templateInfos}></solution-configure-titles>` : "";
  }
  _viewDocumentation(evt) {
    evt.stopPropagation();
    this._telemetry?.logEvent({
      category: TELEMETRY_CATEGORY.DEPLOYMENTS,
      action: "Open Help",
      dimensions: [
        this.card?.title || "",
        this.card?.deployCommonId || "",
        this.card?.deployVersion || "",
        "Details Page"
      ]
    });
    window.open(this.card.learnMoreUrl, "_blank");
  }
  _openItemDetails(evt) {
    evt.stopPropagation();
    this._telemetry?.logEvent({
      category: TELEMETRY_CATEGORY.DEPLOYMENTS,
      action: "Open Item Details",
      dimensions: [
        this.card?.title || "",
        this.card?.deployCommonId || "",
        this.card?.deployVersion || "",
        "Details Page"
      ]
    });
    window.open(this.card.itemUrl, "_blank");
  }
  _getOwnerSection() {
    if (!this._configContextConsumer?.value) {
      return;
    }
    return html`<div class="display-flex padding-bottom-xxl margin-start-end-xxl flex-direction-column"><div class="display-flex justify-between items-baseline"><calcite-label class="font-weight-med label-override" layout=inline scale=l>${this._translations.aboutYourSolutionOwner}</calcite-label></div>${keyed(this.card?.owner, html`<arcgis-user-popup api=4 appearance=outline .baseUrl=${this._configContextConsumer?.value?.authentication?.IsEnterprisePortal ? this._configContextConsumer?.value?.orgUrl : this._configContextConsumer?.value?.orgUrl + "/home/"} class="padding-top-lg" .portal=${this._configContextConsumer?.value?.authentication?.Portal} scale=l show-avatar show-name show-username underline .user=${this._user?.username === this.card?.owner ? this._user : void 0} .username=${this.card?.owner}></arcgis-user-popup>`)}</div>`;
  }
  async _openDiagram(evt) {
    evt.stopPropagation();
    const templates = await this._getTemplates();
    if (templates) {
      this._telemetry?.logEvent({
        category: TELEMETRY_CATEGORY.DEPLOYMENTS,
        action: "View Diagram",
        dimensions: [
          this.card?.title || "",
          this.card?.deployCommonId || "",
          this.card?.deployVersion || "",
          "Details Page"
        ]
      });
      this._templateInfoGraph = templates;
      this._isDiagramOpen = true;
    }
  }
  async _getTemplates() {
    return this.cardRef ? await this.cardRef.getTemplates() : this.card ? await prepareDataForSolutionDisplay(this.card.id, this._configContextConsumer.value.userSession) : void 0;
  }
  _getSolutionVersionCard() {
    const versionString = this._hasNewVersion ? this._translations.newVersionAvailable : this._translations.youHaveTheLatestVersion;
    return html`<div class="padding-xxl display-flex flex-direction-column"><calcite-label class="font-weight-med label-override" layout=inline scale=l slot=heading>${this._translations.solutionVersion.replace("{{version}}", this.card?.deployVersion || "")}</calcite-label><div class="display-flex"><div class="display-flex flex-direction-row padding-top-lg align-items-center"><calcite-icon class="icon-color" icon=clock-forward scale=m></calcite-icon><div class="display-flex flex-direction-column padding-start-xxl"><span>${versionString}</span></div></div></div>${this._hasNewVersion ? html`<calcite-button appearance=outline class="padding-top-lg" kind=neutral @click=${this._openNewVersionSolution} width=full>${this._translations.learnMoreNewVersion}</calcite-button>` : ""}</div>`;
  }
  async _openNewVersionSolution(evt) {
    evt.stopPropagation();
    this._telemetry?.logEvent({
      category: TELEMETRY_CATEGORY.DEPLOYMENTS,
      action: "View Latest Version",
      dimensions: [
        this.card?.title || "",
        this.card?.deployCommonId || "",
        this.card?.deployVersion || ""
      ]
    });
    await new Promise((resolve) => setTimeout(resolve, 100));
    const title = findSolutionTitleByDeployCommonId(this._configContextConsumer.value.allCards, this.card.deployCommonId);
    const url = window.location.href;
    if (title) {
      window.open(url.replace(/deployments\/.+/, title), "_self");
    }
  }
  _getSolutionPanel() {
    const thumbnailUrl = this.card?.thumbnailUrl.replace(/w=\d+/, "w=400");
    const userSession = this._configContextConsumer.value?.userSession;
    return html`<calcite-panel class="font-size-override panel-background-1"><div class="display-flex flex-direction-row"><div class="image-width margin-xl"><img alt=${this.card?.title ?? nothing} src=${thumbnailUrl ? `${thumbnailUrl}&token=${userSession?.token}` : ""}></div><div class="display-flex flex-direction-column"><h1 class="title-font margin-block-start-end-0 padding-end-xxl padding-start-sm padding-top-xxl padding-bottom-xxl line-height-1">${this.card?.title}</h1><div class="display-flex flex-direction-column padding-bottom-xxl padding-start-sm"><div class="display-flex align-items-start padding-bottom-xxl"><div class="font-1 padding-end-1 line-height-xxl">${this.card?.snippet}</div></div><div class="display-flex"><div class="display-flex"><calcite-label class="label-override icon-color" layout=inline><calcite-icon class="icon-color" icon=projects scale=s></calcite-icon>${this._translations.aboutYourSolutionDeployedDate.replace("{{deployedDate}}", this.card?.created || "")}</calcite-label></div></div></div></div></div></calcite-panel>`;
  }
  _getSolutionContents() {
    const justDependencies = [...new Set(this._nonSolutionDependencyItems.map((dep) => dep.controlItemId))];
    return html`<calcite-panel class="panel-background-1 padding-top-xxl"><calcite-accordion class="accordion-bg " icon-position=start scale=l appearance=transparent><calcite-accordion-item class="item-padding" expanded><div class="margin-block-start-end-0 heading-font " slot=content-start>${this._translations.solutionsContentsAndCount.replace("{{numberOfSolutions}}", this.templateInfos.length.toString())}</div><div class="overflow-auto">${this._accordionLoading ? html`<calcite-loader .label=${this._translations.loadingText} scale=m></calcite-loader>` : html`<solution-item-accordion .itemRelationshipDependencies=${justDependencies} .listSelectionMode=${justDependencies.length > 0 ? "multiple" : "single"} .reuseWarning=${this._translations.itemUsedInOtherSolutions} .templateInfos=${this.templateInfos} .typeKeywords=${this.card?.typeKeywords} ${ref(async (el) => {
      if (el) {
        this._accordionRef = el;
      }
    })}></solution-item-accordion>`}</div></calcite-accordion-item></calcite-accordion></calcite-panel>`;
  }
  _getDeleteDialog() {
    return this._deleteDialogOpen ? html`<solution-delete-dialog .card=${this.card} @solutionDeleted=${() => setTimeout(() => this.navTabSelected.emit({ tabType: "deployments" }), 100)} @solutionDeleteDialogBeforeClose=${() => {
      this._deleteDialogOpen = false;
    }} .open=${this._deleteDialogOpen} source="Details Page"></solution-delete-dialog>` : "";
  }
  _getSuccessDeployAlert() {
    return html`<calcite-alert auto-close auto-close-duration=medium icon=check-circle kind=success .label=${this._translations.deploySuccessAlert.replace("{{solutionTitle}}", this.card?.title ?? "")} .open=${this._showSuccessAlert} @calciteAlertClose=${() => {
      this._showSuccessAlert = false;
    }}><div slot=title>${this._translations.deploySuccessAlert.replace("{{solutionTitle}}", this.card?.title ?? "")}</div></calcite-alert>`;
  }
  _renderDiagramDialog() {
    return this._isDiagramOpen ? html`<calcite-dialog class="dialog-y-size dialog-x-size panel-bg-color" .heading=${this._translations.diagramOfTheSolution.replace("{{solution}}", this.card?.title ?? "")} id=${this._translations.diagramOfTheSolution.replace("{{solution}}", this.card?.title ?? "") ?? nothing} modal .open=${this._isDiagramOpen} @calciteDialogClose=${() => {
      this._isDiagramOpen = false;
    }} outside-close-disabled scale=m width=l><solution-item-diagram .diagramKey=${this.diagramKey !== "" ? this.diagramKey : this._configContextConsumer.value?.diagramKey ?? ""} .templateInfoGraph=${this._templateInfoGraph} .typeKeywords=${this.card?.typeKeywords}></solution-item-diagram></calcite-dialog>` : "";
  }
  async _deleteSolution() {
    this._deleteDialogOpen = true;
  }
}
customElement("solution-deployed-card-panel", SolutionDeployedCardPanel);
export {
  SolutionDeployedCardPanel
};
