/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { c as customElement } from "../../chunks/runtime.js";
import { css, html } from "lit";
import { u as useT9n } from "../../chunks/useT9n.js";
import { LitElement, createEvent, safeClassMap } from "@arcgis/lumina";
import { T as TelemetryManager } from "../../chunks/solutions-deploy-app-nav.js";
import { a as BASE_SOLUTIONS_TERMS, x as getUserIsAdmin, B as BASE_DEPLOYED_TERMS, T as TELEMETRY_CATEGORY } from "../../chunks/interfaces.js";
import { createRef, ref } from "lit-html/directives/ref.js";
import { C as CardsFetcher, g as getDeployedSolutions } from "../../chunks/cardFetchingUtils.js";
import { useContextProvider } from "@arcgis/lumina/context";
import { c as configContext, i as isMobileContext } from "../../chunks/deployAppContexts.js";
import { h as findSolutionByTitleOrId, f as findSolutionByTypeKeywordSolutionId } from "../../chunks/cardsHelpers.js";
import "@esri/solution-common";
import "@arcgis/core/identity/IdentityManager.js";
import "@arcgis/core/identity/OAuthInfo.js";
import "@arcgis/core/portal/Portal.js";
import { _ as _appConfig } from "../../chunks/solution-deploy-dialog.js";
import "../solutions-all-shell/customElement.js";
import "../solutions-deployed-shell/customElement.js";
import "../solution-details-panel/customElement.js";
import "../solution-deployed-card-panel/customElement.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.
 */

.back-color-override {
  background-color: var(--calcite-color-foreground-2);
  --calcite-tab-border-color: var(--calcite-color-foreground-3);
}

.display-none {
  display: none !important;
}

.height-100 {
  height: 100%;
}

/* Calcite overrides */

calcite-tab-nav {
  padding-bottom: 6px;
  padding-top: 6px;
}

calcite-tabs {
  --calcite-tab-border-color: var(--calcite-color-border-3);
  --calcite-color-focus: transparent;
  height: 100%;
}

.tab-space-0 {
  --calcite-tab-content-space-y: var(--calcite-spacing-none);
}

.tab-space-md {
  --calcite-tab-content-space-y: var(--calcite-spacing-md);
}

solutions-searchsort-toolbar,
solutions-deploy-app-nav,
solution-details-panel,
solutions-resources-shell,
solutions-deployed-shell,
solutions-all-shell,
calcite-tab-nav,
solution-deployed-card-panel {
  width: 1440px;
  display: block;
  max-width: 96vw;
  padding-right: var(--calcite-spacing-none);
  padding-left: var(--calcite-spacing-none);
  margin-left: auto;
  margin-right: auto;
  box-sizing: border-box;
}

.border {
  height: var(--calcite-spacing-px);
  border-bottom-color: var(--calcite-color-border-3);
  border-bottom-style: solid;
  border-bottom-width: var(--calcite-border-width-sm);
  box-sizing: border-box;
}

.overflow-auto {
  overflow: auto;
}

solution-details-panel {
  scroll-margin-top: 3rem;
}`;
class SolutionsDeployApp extends LitElement {
  constructor() {
    super();
    this.initTitleOrId = "";
    this.sortType = "relevance";
    this.useLocalAppConfig = false;
    this.authentication = void 0;
    this._isLoaded = false;
    this.isMobile = false;
    this._activeTab = "all-solutions";
    this._showDeployedCardFetchFailed = false;
    this._translations = useT9n({ name: "solutions-deploy-app", blocking: true });
    this._agoTerms = `${BASE_SOLUTIONS_TERMS}`;
    this._allCards = [];
    this._allShell = createRef();
    this._allTab = createRef();
    this._allTabTitle = createRef();
    this._resourcesTab = createRef();
    this._resourcesTabTitle = createRef();
    this._categories = [];
    this._configContextProvider = useContextProvider({ context: configContext });
    this._delay = false;
    this._deployAppNav = createRef();
    this._deployedCardPanel = createRef();
    this._deployCardFetchFailedMessage = "";
    this._deployedCardTab = createRef();
    this._deployedCardTabTitle = createRef();
    this._detailsShell = createRef();
    this._detailsTab = createRef();
    this._detailsTabTitle = createRef();
    this._forceInit = false;
    this._getSuggested = false;
    this._isMobileContextProvider = useContextProvider({ context: isMobileContext });
    this._mySolutionsShell = createRef();
    this._mySolutionsTab = createRef();
    this._mySolutionsTabTitle = createRef();
    this._sortField = "relevance";
    this._sortOrder = "desc";
    this._telemetryManager = new TelemetryManager();
    this.deployAppTabSelected = createEvent();
    this.deployedCardFetchFailed = createEvent();
    this.detailsCardSelected = createEvent();
    this.deployedCardSelected = createEvent();
    this.metaTagStringsReady = createEvent();
    this.tabChanged = createEvent();
    this.listenOn(window, "detailsCardSelected", this._detailsCardSelected);
    this.listenOn(window, "deployedCardSelected", this._deployedCardSelected);
    this.listenOn(window, "displayDeployedCard", this._handleDeployedCardDisplay);
    this.listenOn(window, "navTabSelected", this._setActiveTab);
    this.listenOn(window, "forceSelectTab", (evt) => this.selectTab(evt.detail, {}));
    this._mediaQueryChange = this._mediaQueryChange.bind(this);
  }
  static {
    this.properties = { appConfig: 1, initTab: 1, initTitleOrId: 1, sortType: 1, useLocalAppConfig: [5, {}, { type: Boolean }], authentication: [16, {}, { state: true }], _isLoaded: [16, {}, { state: true }], isMobile: [16, {}, { state: true }], _activeTab: [16, {}, { state: true }], _showDeployedCardFetchFailed: [16, {}, { state: true }], _translations: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  get _telemetry() {
    return this._configContextProvider.value?.telemetrySession;
  }
  get _isDisconnectedEnvironment() {
    return this._configContextProvider.value?.isEnterprise === true && this._configContextProvider.value?.authentication?.CanSearchArcGISOnline === false;
  }
  async selectTab(tab, filters) {
    console.log("selectTab");
    if (this._isLoaded || this._forceInit) {
      const searchOptions = this._getDefaultSearchOptions(filters);
      switch (tab.tabType) {
        case "all-solutions":
          this._allTab.value.selected = true;
          this._allTabTitle.value.selected = true;
          if (searchOptions) {
            await this._allShell.value?.searchSolutions(searchOptions);
          }
          break;
        case "resources":
          this._resourcesTab.value.selected = true;
          this._resourcesTabTitle.value.selected = true;
          break;
        case "deployed-card":
          if (this.authentication?.IsSignedIn) {
            this._forceInit = true;
            this._isLoaded = false;
            if (this._cardFetcherDeployed) {
              await this._getDeployedSolution(tab.tabTitleOrId);
            }
            if (this._deployedSolutions?.cards?.length > 0) {
              let card;
              this._deployedSolutions.cards.some((c) => {
                if (c.id === tab.tabTitleOrId) {
                  card = c;
                  this.deployedCardSelected.emit({ card });
                  return true;
                } else {
                  return false;
                }
              });
              this._isLoaded = true;
              this._forceInit = false;
            } else {
              this._isLoaded = true;
              this._forceInit = false;
              return this.selectTab({ tabTitleOrId: "", tabType: "deployments" }, filters);
            }
            break;
          } else {
            await this.authentication?.signIn();
          }
        case "details":
          if (this._allCards) {
            let card = findSolutionByTitleOrId(this._allCards, tab.tabTitleOrId);
            card = card ? card : findSolutionByTypeKeywordSolutionId(this._allCards, tab.tabTitleOrId);
            if (card) {
              this._detailsTab.value.selected = true;
              this._detailsTabTitle.value.selected = true;
              this.detailsCardSelected.emit(card);
            } else {
              tab.tabType = "all-solutions";
              this._allTab.value.selected = true;
              this._allTabTitle.value.selected = true;
            }
          }
          break;
        case "deployments":
          this._mySolutionsTab.value.selected = true;
          this._mySolutionsTabTitle.value.selected = true;
          if (searchOptions) {
            console.log(this._searchSortToolbar);
            await this._mySolutionsShell.value?.searchSolutions(searchOptions);
          }
          break;
      }
      this._setActiveTab(new CustomEvent("setActiveTab", { detail: tab }));
      this._blurTabs();
      if (this._showDeployedCardFetchFailed) {
        this.deployedCardFetchFailed.emit({ message: this._deployCardFetchFailedMessage, title: this._translations.failedToOpen });
        this._showDeployedCardFetchFailed = false;
      }
      return true;
    } else {
      this._initTab = tab;
      this._initFilters = filters;
      return false;
    }
  }
  async connectedCallback() {
    super.connectedCallback();
    this._mediaQuery = window.matchMedia("(max-width: 800px)");
    this._mediaQuery.addEventListener("change", this._mediaQueryChange);
    this._mediaQueryChange(this._mediaQuery);
  }
  async load() {
    if (this.useLocalAppConfig) {
      this.appConfig = _appConfig;
    }
  }
  render() {
    const loaderCss = this._isLoaded ? "display-none" : "";
    const tabsCss = this._isLoaded ? "" : "display-none";
    return html`<calcite-shell><solutions-deploy-app-nav .appConfig=${this.appConfig} .initTab=${this.initTab} @authInit=${this._handleAuthInit} slot=header ${ref(this._deployAppNav)}></solutions-deploy-app-nav>${this._isSearchToolbarShowing() && html`<div class="border" slot=header></div>` || ""}<solutions-searchsort-toolbar slot=header ${ref(async (el) => {
      if (el) {
        await this._deployAppNav.value?.componentOnReady();
        console.log("this is not working right on page refresh need to fiugure out another way");
        if (el.scope === void 0) {
          this._searchSortToolbar = el;
          console.log(this._initFilters);
        }
      }
    })}></solutions-searchsort-toolbar><calcite-loader class=${safeClassMap(loaderCss)} id=solutions-loader .label=${this._translations.fetchingAllSolutions}></calcite-loader><calcite-tabs class=${safeClassMap(tabsCss)} scale=l><calcite-tab-nav class="display-none" @calciteTabChange=${this._handleTabChanged} slot=title-group><calcite-tab-title ${ref(this._allTabTitle)}>${this._translations.allSolutions}</calcite-tab-title><calcite-tab-title ${ref(this._mySolutionsTabTitle)}>${this._translations.mySolutions}</calcite-tab-title><calcite-tab-title ${ref(this._resourcesTabTitle)}>${this._translations.solutionResources}</calcite-tab-title><calcite-tab-title class="display-none" ${ref(this._detailsTabTitle)}></calcite-tab-title><calcite-tab-title class="display-none" ${ref(this._deployedCardTabTitle)}></calcite-tab-title></calcite-tab-nav><calcite-tab class="back-color-override tab-space-0" selected ${ref(this._allTab)}><solutions-all-shell class="height-100" ${ref(this._allShell)}></solutions-all-shell></calcite-tab><calcite-tab class="back-color-override tab-space-0" ${ref(this._mySolutionsTab)}><solutions-deployed-shell class="height-100" ${ref(this._mySolutionsShell)}></solutions-deployed-shell></calcite-tab><calcite-tab class="back-color-override tab-space-0" ${ref(this._resourcesTab)}><solutions-resources-shell class="height-100"></solutions-resources-shell></calcite-tab><calcite-tab class="back-color-override" ${ref(this._detailsTab)}><solution-details-panel class="height-100" ${ref(this._detailsShell)}></solution-details-panel></calcite-tab><calcite-tab class="back-color-override tab-space-0" ${ref(this._deployedCardTab)}><solution-deployed-card-panel class="shell-container height-100" ${ref(this._deployedCardPanel)}></solution-deployed-card-panel></calcite-tab></calcite-tabs></calcite-shell>`;
  }
  loaded() {
    this._setScrollbarGutters();
  }
  disconnectedCallback() {
    super.disconnectedCallback();
    this._mediaQuery?.removeEventListener("change", this._mediaQueryChange);
  }
  async _handleAuthInit(evt) {
    const config = evt.detail;
    if (!config.telemetrySession) {
      config.telemetrySession = TelemetryManager.getDisabledSession();
    }
    this._configContextProvider.setValue(config);
    if (config.authentication) {
      this.authentication = config.authentication;
    }
    this._cardFetcherDeployed = new CardsFetcher(config.locale, config.orgUrl, config.portalURL);
    this._cardsFetcher = new CardsFetcher(config.locale, config.orgUrl, config.portalURL);
    if (!this._isDisconnectedEnvironment) {
      await this._getSolutions(config.primarySolutionsGroupId, config.agoBasedEnterpriseSolutionsGroupId);
    }
    this._configContextProvider.value.allCards = this._allCards;
    this._configContextProvider.value.anonAgolSession = this._cardsFetcher.anonAgolSession;
    this._configContextProvider.value.agolPortalUrl = this._cardsFetcher.agolPortalUrl;
    await this._initializeTelemetry();
    this._isLoaded = true;
    this._setRefreshInterval();
    if (this._initTab) {
      this.selectTab(this._initTab, this._initFilters);
      this._logTabViewTelemetry(this._initTab.tabType);
      this._initTab = void 0;
      this._initFilters = void 0;
    } else {
      if (this.authentication?.IsSignedIn) {
        const isDetailsOrDeployedCard = this.initTab === "details" || this.initTab === "deployed-card";
        if (!isDetailsOrDeployedCard) {
          this._logTabViewTelemetry(this._activeTab);
          this._emitMetaTagStrings(this._activeTab);
        }
      }
    }
  }
  _mediaQueryChange(event) {
    this.isMobile = event.matches;
    this._isMobileContextProvider.setValue(this.isMobile);
  }
  _setActiveTab(evt) {
    const navTab = evt.detail;
    const tabType = navTab.tabType;
    const shouldLogTelemetry = this._activeTab !== tabType;
    this._activeTab = tabType;
    if (shouldLogTelemetry) {
      this._logTabViewTelemetry(tabType);
    }
    switch (tabType) {
      case "all-solutions":
        this._allTabTitle.value?.click();
        break;
      case "deployments":
        this._mySolutionsTabTitle.value?.click();
        break;
      case "resources":
        this._resourcesTabTitle.value?.click();
        break;
      case "deployed-card":
        this._deployedCardTabTitle.value?.click();
        break;
      case "details":
        this._detailsTabTitle.value?.click();
        break;
    }
    if (tabType !== "details" && tabType !== "deployed-card") {
      this._deployAppNav.value.activateMenuItem(tabType);
      this.deployAppTabSelected.emit(tabType);
      this._emitMetaTagStrings(tabType);
    }
  }
  _logTabViewTelemetry(tabType, solutionCard) {
    let telemetryCategory;
    switch (tabType) {
      case "all-solutions":
        telemetryCategory = TELEMETRY_CATEGORY.ALL_SOLUTIONS;
        break;
      case "deployments":
        telemetryCategory = TELEMETRY_CATEGORY.DEPLOYMENTS;
        break;
      case "resources":
        telemetryCategory = TELEMETRY_CATEGORY.RESOURCES;
        break;
      case "details":
        telemetryCategory = TELEMETRY_CATEGORY.SOLUTION_DETAILS;
        break;
      case "deployed-card":
        telemetryCategory = TELEMETRY_CATEGORY.DEPLOYMENTS;
        break;
    }
    if ((tabType === "details" || tabType === "deployed-card") && !solutionCard) {
      return;
    }
    if (telemetryCategory) {
      const dimensions = [];
      if ((tabType === "details" || tabType === "deployed-card") && solutionCard) {
        const card = solutionCard;
        dimensions.push(card.title || "");
        dimensions.push(card.deployCommonId || "");
        dimensions.push(card.deployVersion || "");
      }
      const action = tabType === "deployed-card" ? "Open" : "View";
      this._telemetry?.logEvent({
        category: telemetryCategory,
        action,
        dimensions: dimensions.length > 0 ? dimensions : void 0
      });
    }
  }
  _emitMetaTagStrings(tabType, detailTemplate) {
    let title = "";
    let description = "";
    switch (tabType) {
      case "all-solutions":
        title = this._translations.metaAllSolutionsTitle;
        description = this._translations.metaAllSolutionsDescription;
        break;
      case "deployments":
      case "deployed-card":
        title = this._translations.metaDeploymentsTitle;
        description = this._translations.metaDeploymentsDescription;
        break;
      case "resources":
        title = this._translations.metaResourcesTitle;
        description = this._translations.metaResourcesDescription;
        break;
      case "details":
        if (detailTemplate) {
          title = this._translations.metaDetailsTitle.replace("{title}", detailTemplate.title);
          description = detailTemplate.snippet;
        }
        break;
    }
    this.metaTagStringsReady.emit({
      pageType: tabType,
      title,
      description,
      detailTemplate
    });
  }
  _handleTabChanged(evt) {
    console.log("=======================tabCg=haned here too======================================");
    console.log(evt);
    if (this._activeTab === "deployments") ;
    this.tabChanged.emit(this._activeTab);
  }
  _detailsCardSelected(evt) {
    this._activeTab = "details";
    this._detailsTabTitle.value.selected = true;
    this._detailsTab.value.selected = true;
    this._deployAppNav.value.clearMenuItems();
    if (evt?.detail) {
      this._selectedDetailsCard = evt.detail;
    }
    this._logTabViewTelemetry("details", this._selectedDetailsCard);
    this._emitMetaTagStrings("details", this._selectedDetailsCard);
  }
  _deployedCardSelected(evt) {
    this._activeTab = "deployed-card";
    this._deployedCardTabTitle.value.selected = true;
    this._deployedCardTab.value.selected = true;
    this._deployAppNav.value.clearMenuItems();
    if (evt?.detail?.card) {
      this._selectedDeployedCard = evt.detail.card;
    }
    this._logTabViewTelemetry("deployed-card", this._selectedDeployedCard);
    this._emitMetaTagStrings("deployed-card");
  }
  _handleDeployedCardDisplay(evt) {
    const { card, cardRef } = evt.detail;
    this.deployedCardSelected.emit({ card, cardRef });
  }
  async _initializeTelemetry() {
    const config = this._configContextProvider.value;
    if (!this.authentication || !config)
      return;
    const telemetrySession = await this._telemetryManager.initializeTelemetry(this.authentication, config);
    this._configContextProvider.value.telemetrySession = telemetrySession;
  }
  async _getSolutions(primarySolutionsGroupId, agoBasedEnterpriseSolutionsGroupId) {
    if (this._isDisconnectedEnvironment) {
      return [];
    }
    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,
      "num": 100
    }, primarySolutionsGroupId, agoBasedEnterpriseSolutionsGroupId, this._configContextProvider.value.userSession, this._configContextProvider.value.isEnterprise, {
      "num": 1e3
    });
    if (this._allCards.length === 0 && fetchedCards?.cards) {
      this._allCards = fetchedCards?.cards;
    }
    return this._allCards;
  }
  async _getDeployedSolution(id) {
    const authentication = this._configContextProvider.value.authentication;
    const userSession = this._configContextProvider.value.userSession;
    if (authentication && userSession && authentication.IsSignedIn) {
      const isOrgAdmin = getUserIsAdmin(authentication);
      try {
        const deployedSolutions = await getDeployedSolutions(authentication, userSession, this._cardsFetcher, this._cardFetcherDeployed, BASE_DEPLOYED_TERMS, "created", "desc", false, [], [], isOrgAdmin ? `My organization's solutions` : "My solutions", id);
        if (deployedSolutions.cards.length === 0 || deployedSolutions.cards[0].typeKeywords.indexOf("Deployed") < 0) {
          this._deployCardFetchFailedMessage = this._translations.failedToFetchNotSolution.replace("{{ITEMID}}", id);
          this._showDeployedCardFetchFailed = true;
        } else {
          this._deployedSolutions = deployedSolutions;
        }
      } catch (error) {
        const m = error.message;
        if (m.indexOf("CONT_0001") > -1 || m.indexOf("Item does not exist or is inaccessible.") > -1) {
          this._deployCardFetchFailedMessage = this._translations.failedToFetchWrongId.replace("{{ITEMID}}", id);
          this._showDeployedCardFetchFailed = true;
        } else if (m.indexOf("GWM_0003") > -1 || m.indexOf("You do not have permissions to access this resource or perform this operation.") > -1) {
          this._deployCardFetchFailedMessage = this._translations.failedToFetchWrongPermissions.replace("{{ITEMID}}", id);
          this._showDeployedCardFetchFailed = true;
        } else {
          this._showDeployedCardFetchFailed = true;
          this._deployCardFetchFailedMessage = "";
        }
        console.warn(error);
      }
    }
  }
  _blurTabs() {
    this._allTabTitle.value?.blur();
    this._resourcesTabTitle.value?.blur();
    this._detailsTabTitle.value?.blur();
    this._mySolutionsTabTitle.value?.blur();
  }
  _isSearchToolbarShowing() {
    return this._activeTab === "all-solutions" || this._activeTab === "deployments" && this.authentication?.IsSignedIn === true;
  }
  _getDefaultSearchOptions(filters) {
    let searchOptions = void 0;
    if (filters) {
      const domain = filters.domain;
      const industry = filters.industry;
      const offerType = filters.offerType;
      const searchTerm = filters.searchTerm;
      const displayValue = "";
      let sortType = filters.sortField;
      const owner = filters.owner;
      searchOptions = domain || industry ? {
        type: domain ? "domain" : industry ? "industry" : ""
      } : void 0;
      if (domain) {
        searchOptions = searchOptions ? { ...searchOptions, domain } : { domain };
      }
      if (industry) {
        searchOptions = searchOptions ? { ...searchOptions, industry } : { industry };
      }
      if (searchTerm) {
        searchOptions = searchOptions ? { ...searchOptions, searchTerm } : { searchTerm };
      }
      if (searchOptions) {
        searchOptions = { ...searchOptions, displayValue };
      }
      if (sortType) {
        searchOptions = searchOptions ? { ...searchOptions, sortType } : { sortType };
      }
      if (offerType) {
        sortType = offerType.toLowerCase();
        searchOptions = searchOptions ? { ...searchOptions, sortType } : { sortType };
      }
      if (owner) {
        searchOptions = searchOptions ? { ...searchOptions, owner } : { owner };
      }
    }
    return searchOptions;
  }
  _setScrollbarGutters() {
    const detailsElement = this._detailsTab.value?.shadowRoot?.firstElementChild;
    if (detailsElement?.style) {
      detailsElement.style.scrollbarGutter = "stable both-edges";
    }
    const deployedCardElement = this._deployedCardTab.value?.shadowRoot?.firstElementChild;
    if (deployedCardElement?.style) {
      deployedCardElement.style.scrollbarGutter = "stable both-edges";
    }
  }
  _setRefreshInterval() {
    const { userSession, authentication } = this._configContextProvider.value;
    if (userSession && userSession.tokenDuration && authentication?.IsSignedIn) {
      const currTime = Date.now();
      const difference = authentication.Credential?.expires - currTime;
      const refreshInterval = difference * 0.95;
      setInterval(async () => {
        await userSession.refreshCredentials();
      }, refreshInterval);
    }
  }
}
customElement("solutions-deploy-app", SolutionsDeployApp);
export {
  SolutionsDeployApp
};
