/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { c as customElement } from "../../chunks/runtime.js";
import { u as useT9n } from "../../chunks/useT9n.js";
import { LitElement, createEvent, safeClassMap } from "@arcgis/lumina";
import { useContextConsumer } from "@arcgis/lumina/context";
import { css, html } from "lit";
import { I as ITEM_TITLE_LENGTH, T as TELEMETRY_CATEGORY } from "../../chunks/interfaces.js";
import { createRef, ref } from "lit-html/directives/ref.js";
import { c as configContext } from "../../chunks/deployAppContexts.js";
import * as common from "@esri/solution-common";
import { updateGroup, updateItem, updateItemExtended } from "@esri/solution-common";
import { h as hasInvalidChars } from "../../chunks/helpers.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.
 */

.display-flex {
  display: flex;
}

.display-none {
  display: none;
}

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

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

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

.font-style-1 {
  font-size: 1rem;
  color: var(--calcite-color-text-2);
}

.margin-top-0 {
  margin-top: 0;
}

.padding-bottom-2 {
  padding-bottom: 2rem;
}

.padding-left-2 {
  padding-left: 2rem;
}

.padding-right-2 {
  padding-right: 2rem;
}

.padding-end-1 {
  padding-inline-end: 1rem;
}

.padding-end-1-2 {
  padding-inline-end: .5rem;
}

.width-full {
  width: 100%;
}

.justify-content-space {
  justify-content: space-between;
}`;
class SolutionConfigureTitles extends LitElement {
  constructor() {
    super(...arguments);
    this.open = false;
    this.source = "Card Dropdown";
    this.solutionData = {};
    this.templateInfos = [];
    this._saveDisabled = false;
    this._displayTemplateInfos = [];
    this._hasNameLengthError = false;
    this._nonSolutionDependencyItems = [];
    this._solutionItemsTitlesUpdating = false;
    this._translations = useT9n({ name: "solution-configure-titles", blocking: true });
    this._configContextConsumer = useContextConsumer({
      context: configContext,
      subscribe: true
    });
    this._defaultPrefix = "";
    this._defaultSuffix = "";
    this._loadingDefaultPrefix = false;
    this._loadingDefaultSuffix = false;
    this._prefixRef = createRef();
    this._prefixValue = "";
    this._suffixRef = createRef();
    this._suffixValue = "";
    this._templateInfos = [];
    this._originalTitles = [];
    this.solutionConfigureTitlesBeforeClose = createEvent();
    this.solutionItemsTitlesChanged = createEvent();
  }
  static {
    this.properties = { card: [0, {}, { attribute: false }], open: [5, {}, { type: Boolean }], source: 1, solutionData: 1, templateInfos: [0, {}, { attribute: false }], _saveDisabled: [16, {}, { state: true }], _displayTemplateInfos: [16, {}, { state: true }], _hasNameLengthError: [16, {}, { state: true }], _nonSolutionDependencyItems: [16, {}, { state: true }], _solutionItemsTitlesUpdating: [16, {}, { state: true }], _translations: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  async willUpdate(changes) {
    if (changes.has("templateInfos")) {
      this._templateInfos = JSON.parse(JSON.stringify(this.templateInfos));
      this._updateTemplates();
    }
    if (changes.has("open")) {
      const oldValue = changes.get("open");
      if (this.open && !oldValue) {
        await this._updatePrefixSuffix();
        this._templateInfos = JSON.parse(JSON.stringify(this.templateInfos));
        this._originalTitles = this._templateInfos.map((t) => ({ id: t.id, title: t.title }));
        this._updateTemplates();
        const relatedInfos = await getRelatedSolutionsInfos(this._configContextConsumer.value.userSession, this.card);
        this._nonSolutionDependencyItems = relatedInfos._nonSolutionDependencyItems;
        await this._accordionRef?.expandFirstItem();
        this._accordionRef?.expandItems(relatedInfos.uniqueIitemIds);
      }
    }
  }
  get _telemetry() {
    return this._configContextConsumer.value?.telemetrySession;
  }
  async load() {
    this._updateTemplates();
    await this._updatePrefixSuffix();
  }
  async _updatePrefixSuffix() {
    this.solutionData = await common.getItemDataAsJson(this.card.id, this._configContextConsumer.value.userSession);
    if (this.solutionData.titles?.prefix) {
      this._loadingDefaultPrefix = true;
      this._defaultPrefix = this.solutionData.titles.prefix;
      this._prefixValue = this.solutionData.titles.prefix;
    }
    if (this.solutionData.titles?.suffix) {
      this._loadingDefaultSuffix = true;
      this._defaultSuffix = this.solutionData.titles.suffix;
      this._suffixValue = this.solutionData.titles.suffix;
    }
  }
  render() {
    return html`<calcite-dialog .heading=${this.card.title} modal @calciteDialogBeforeClose=${() => {
      this.solutionConfigureTitlesBeforeClose.emit();
    }} .open=${this.open} outside-close-disabled width=l>${this._getPrefixSuffixControls()}${this._getAccordion()}${this._getDialogButtons()}</calcite-dialog>`;
  }
  _getPrefixSuffixControls() {
    const prefixHasInvalidChars = hasInvalidChars(this._prefixValue, "item");
    const prefixIsLengthExceeded = this._hasNameLengthError && this._prefixValue.length > 0;
    const validPrefixChars = !prefixHasInvalidChars;
    const validPrefixLength = !prefixIsLengthExceeded;
    const prefixCharsMessageClass = validPrefixChars ? "display-none" : "";
    const prefixLengthMessageClass = validPrefixLength ? "display-none" : "";
    const isValidPrefix = validPrefixChars && validPrefixLength ? "valid" : "invalid";
    const suffixHasInvalidChars = hasInvalidChars(this._suffixValue, "item");
    const suffixIsLengthExceeded = this._hasNameLengthError && this._suffixValue.length > 0;
    const validSuffixChars = !suffixHasInvalidChars;
    const validSuffixLength = !suffixIsLengthExceeded;
    const suffixCharsMessageClass = validSuffixChars ? "display-none" : "";
    const suffixLengthMessageClass = validSuffixLength ? "display-none" : "";
    const isValidSuffix = validSuffixChars && validSuffixLength ? "valid" : "invalid";
    this._saveDisabled = !validPrefixChars || !validPrefixLength || !validSuffixChars || !validSuffixLength || !this._hasChanges();
    return html`<div class="display-flex flex-direction-column padding-left-2 padding-right-2"><calcite-label scale=l class="font-weight-medium">${this._translations.configureTitlesDialogHeader}</calcite-label><p class="font-style-1 margin-top-0">${this._translations.addPrefixOrSuffixToItems}</p><div class="display-flex flex-direction-row justify-content-space"><calcite-label class="width-full padding-end-1" scale=l>${this._translations.prefixToAddToItems}<calcite-input clearable @blur=${this._prefixInput} @input=${this._prefixInput} .placeholder=${this._translations.enterPrefixPlaceholder} .status=${isValidPrefix} .value=${this._prefixValue} ${ref(this._prefixRef)}></calcite-input><calcite-input-message class=${safeClassMap(prefixCharsMessageClass)} icon=exclamation-mark-triangle status=invalid>${this._translations.invalidPrefixOrSuffixCharsError}</calcite-input-message><calcite-input-message class=${safeClassMap(prefixLengthMessageClass)} icon=exclamation-mark-triangle status=invalid>${this._translations.invalidPrefixOrSuffixLengthError}</calcite-input-message></calcite-label><calcite-label class="width-full" scale=l>${this._translations.suffixToAddToItems}<calcite-input clearable @blur=${this._suffixInput} @input=${this._suffixInput} .placeholder=${this._translations.enterSuffixPlaceholder} .status=${isValidSuffix} .value=${this._suffixValue} ${ref(this._suffixRef)}></calcite-input><calcite-input-message class=${safeClassMap(suffixCharsMessageClass)} icon=exclamation-mark-triangle status=invalid>${this._translations.invalidPrefixOrSuffixCharsError}</calcite-input-message><calcite-input-message class=${safeClassMap(suffixLengthMessageClass)} icon=exclamation-mark-triangle status=invalid>${this._translations.invalidPrefixOrSuffixLengthError}</calcite-input-message></calcite-label></div></div>`;
  }
  _getAccordion() {
    const justDependencies = [...new Set(this._nonSolutionDependencyItems.map((dep) => dep.controlItemId))];
    return html`<div class="display-flex flex-direction-column padding-left-2 padding-right-2 padding-bottom-2"><p class="font-style-1 margin-top-0">${this._translations.previewTheChanges}</p><solution-item-accordion .itemRelationshipDependencies=${justDependencies} list-selection-mode=multiple .reuseWarning=${this._translations.itemDependencyReuseWarning} .templateInfos=${this._displayTemplateInfos} .typeKeywords=${this.card?.typeKeywords} ${ref(async (el) => {
      if (el) {
        this._accordionRef = el;
      }
    })}></solution-item-accordion></div>`;
  }
  _getDialogButtons() {
    return html`<div slot=footer-end><calcite-button appearance=outline class="padding-end-1-2" kind=brand @click=${this._closeDialog}>${this._translations.cancelTheDialog}</calcite-button><calcite-button .disabled=${this._saveDisabled} kind=brand .loading=${this._solutionItemsTitlesUpdating} @click=${this._commitNameChanges}>${this._translations.applyChangesAndCloseTheDialog}</calcite-button></div>`;
  }
  _prefixInput() {
    clearTimeout(this._textInputTimeout);
    this._textInputTimeout = setTimeout(() => {
      this._prefixValue = this._prefixRef.value?.value || "";
      this._updateTemplates();
    }, 500);
  }
  _suffixInput() {
    clearTimeout(this._textInputTimeout);
    this._textInputTimeout = setTimeout(() => {
      this._suffixValue = this._suffixRef.value?.value || "";
      this._updateTemplates();
    }, 500);
  }
  _updateTemplates() {
    this._templateInfos = this._templateInfos.map((t) => {
      if (this._loadingDefaultPrefix && t.title.startsWith(this._prefixValue)) {
        t.title = this._replaceStart(t.title, this._prefixValue, "");
      }
      if (this._loadingDefaultSuffix && t.title.endsWith(this._suffixValue)) {
        t.title = this._replaceAtEnd(t.title, this._suffixValue, "");
      }
      return t;
    });
    const _templateInfos = JSON.parse(JSON.stringify(this._templateInfos));
    this._hasNameLengthError = false;
    this._displayTemplateInfos = _templateInfos.map((t) => {
      const hasInputPrefix = this._prefixValue !== "";
      const hasInputSuffix = this._suffixValue !== "";
      const hasStoredPrefix = this._defaultPrefix !== "";
      const hasStoredSuffix = this._defaultSuffix !== "";
      let titleWithPrefix = t.title;
      if (hasInputPrefix) {
        if (hasStoredPrefix) {
          const titleStartsWithStoredPrefix = this._originalTitles.find((ot) => ot.id === t.id)?.title.startsWith(this._defaultPrefix);
          if (titleStartsWithStoredPrefix) {
            titleWithPrefix = this._applyPrefixWithDuplicateCheck(t.title, this._prefixValue);
          } else {
            if (this._prefixValue !== this._defaultPrefix) {
              titleWithPrefix = this._applyPrefixWithDuplicateCheck(t.title, this._prefixValue);
            }
          }
        } else {
          titleWithPrefix = this._applyPrefixWithDuplicateCheck(t.title, this._prefixValue);
        }
      }
      let finalTitle = titleWithPrefix;
      if (hasInputSuffix) {
        if (hasStoredSuffix) {
          const titleEndsWithStoredSuffix = this._originalTitles.find((ot) => ot.id === t.id)?.title.endsWith(this._defaultSuffix);
          if (titleEndsWithStoredSuffix) {
            finalTitle = this._applySuffixWithDuplicateCheck(titleWithPrefix, this._suffixValue);
          } else {
            if (this._suffixValue !== this._defaultSuffix) {
              finalTitle = this._applySuffixWithDuplicateCheck(titleWithPrefix, this._suffixValue);
            }
          }
        } else {
          finalTitle = this._applySuffixWithDuplicateCheck(titleWithPrefix, this._suffixValue);
        }
      }
      t.title = finalTitle;
      if (!this._hasNameLengthError) {
        this._hasNameLengthError = t.title.length > ITEM_TITLE_LENGTH;
      }
      return t;
    });
    this._loadingDefaultPrefix = false;
    this._loadingDefaultSuffix = false;
  }
  _replaceStart(originalString, searchString, replaceString) {
    return originalString.startsWith(searchString) ? `${replaceString}${originalString.slice(searchString.length)}` : originalString;
  }
  _replaceAtEnd(originalString, searchString, replaceString) {
    return originalString.endsWith(searchString) ? `${originalString.substring(0, originalString.length - searchString.length)}${replaceString}` : originalString;
  }
  _applyPrefixWithDuplicateCheck(title, prefix) {
    if (!prefix) {
      return title;
    }
    if (title.startsWith(prefix)) {
      return title;
    }
    return prefix + title;
  }
  _applySuffixWithDuplicateCheck(title, suffix) {
    if (!suffix) {
      return title;
    }
    if (title.endsWith(suffix)) {
      return title;
    }
    return title + suffix;
  }
  _hasChanges() {
    const prefixChangedFromDefault = this._defaultPrefix !== this._prefixValue;
    const suffixChangedFromDefault = this._defaultSuffix !== this._suffixValue;
    const templatesChanged = this._displayTemplateInfos.some((d) => {
      const originalItem = this._originalTitles.find((o) => o.id === d.id);
      return originalItem && originalItem.title !== d.title;
    });
    return templatesChanged || prefixChangedFromDefault || suffixChangedFromDefault;
  }
  _closeDialog() {
    this.open = false;
  }
  async _commitNameChanges() {
    if (this._hasChanges()) {
      this._telemetry?.logEvent({
        category: TELEMETRY_CATEGORY.DEPLOYMENTS,
        action: "Rename Items",
        dimensions: [
          this.card?.title || "",
          this.card?.deployCommonId || "",
          this.card?.deployVersion || "",
          this.source
        ]
      });
      this._solutionItemsTitlesUpdating = true;
      const updateRequests = this._displayTemplateInfos.reduce((prev, cur) => {
        const updateOptions = {
          id: cur.id,
          title: cur.title
        };
        prev.push(cur.type === "Group" ? updateGroup(updateOptions, this._configContextConsumer.value.userSession) : updateItem(updateOptions, this._configContextConsumer.value.userSession));
        return prev;
      }, []);
      if (this.solutionData?.templates) {
        const itemInfo = {
          id: this.card.id
        };
        const data = {
          ...this.solutionData,
          titles: {
            prefix: this._prefixValue,
            suffix: this._suffixValue
          }
        };
        updateRequests.push(updateItemExtended(itemInfo, data, this._configContextConsumer.value.userSession));
      }
      await Promise.all(updateRequests);
      this._solutionItemsTitlesUpdating = false;
      this.solutionItemsTitlesChanged.emit();
    }
    this._closeDialog();
  }
}
customElement("solution-configure-titles", SolutionConfigureTitles);
export {
  SolutionConfigureTitles
};
