/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { c as b } from "../../chunks/runtime.js";
import { b as m } from "../../chunks/interfaces.js";
import { joinAppProxies as y } from "templates-common-library/functionality/proxy";
import { c as _, e as g } from "../../chunks/mapViewUtils.js";
import { u as v } from "../../chunks/useT9n.js";
import { css as I, nothing as c, html as l } from "lit";
import { createRef as p, ref as d } from "lit-html/directives/ref.js";
import { LitElement as $, createEvent as r, noShadowRoot as L, safeClassMap as f } from "@arcgis/lumina";
import { defineCustomElements as w } from "@arcgis/instant-apps-components/loader";
import { f as M } from "../../chunks/helpers.js";
import S from "@arcgis/core/config.js";
import "@arcgis/core/views/MapView.js";
import T from "@arcgis/core/WebMap.js";
const C = I`@layer{:host{display:block;--calcite-label-margin-bottom: 0;--calcite-block-padding: 0}.map-height{height:calc(100% - 53px)}.height-full{height:100%}.height-49-px{height:49px}.box-shadow{box-shadow:none!important}.visibility-hidden-1{visibility:hidden;height:1px}.hidden{visibility:hidden!important}.display-flex{display:flex}.display-none{display:none}.display-block{display:block}.absolute-right{position:absolute;right:0;left:unset}.esri-ui-inner-container.esri-ui-corner-container{direction:ltr}html[dir=rtl] .absolute-right{left:0;right:unset}.panel-header-override{--calcite-panel-header-content-space: 0px;--calcite-internal-panel-action-spacing: 0px !important}@media only screen and (max-width:1024px){.esri-zoom{display:none!important}}calcite-action-bar{--calcite-internal-action-bar-gap: 0px;--calcite-internal-action-bar-padding: 0px}}`;
class W extends $ {
  constructor() {
    super(), this.defaultWebmapId = "", this.defaultLayerId = "", this.enableHome = !1, this.enableLegend = !1, this.enableLayerList = !0, this.enableFloorFilter = !1, this.enableFullscreen = !1, this.enableShare = !1, this.enableMapLayerPicker = !1, this.enableMapPicker = !1, this.enableSingleExpand = !1, this.enableSearch = !1, this.enableBasemap = !1, this.featureSelectionMode = "multiple", this.hide = !1, this.zoomToolsSize = "m", this.mapInfos = [], this.mapWidgetsIndex = 0, this.mapWidgetsPosition = "top-leading", this.mobileMapWidgetsPosition = "top-right", this.mapWidgetsSize = "m", this.stackTools = !1, this.mapToolsOrder = [], this.mobileToolsOrder = [], this.isMapLayout = !1, this.shareIncludeEmbed = !1, this.shareIncludeSocial = !1, this.selectedFeaturesIds = [], this.showOnlyUpdatableLayers = !1, this.isMobile = !1, this.enableSelectionTool = !1, this.visibilityIcon = "eyeball", this.pasteEnabled = !1, this.mapComponentId = "arcgis-map", this.showCopyPasteActions = !1, this._configLayerOrderDefined = !1, this._translations = v({ name: "map-card", blocking: !0 }), this._toolInfos = [], this._filterActive = !1, this._layerIds = [], this._enabledLayerIds = [], this._defaultWebmapHonored = !1, this._loadedId = "", this._mapDiv = p(), this._mapComponent = p(), this._mapPicker = p(), this._mapTools = p(), this._mobMapTools = p(), this._mapLayerPicker = p(), this._selectedWebMapId = "", this._isValidWebMap = !0, this.mapChanged = r(), this.beforeMapChanged = r(), this.toggleFilter = r(), this.clearSelection = r(), this.copyFeatures = r(), this.pasteFeatures = r(), this.editMultipleFeatures = r(), this.featuresCopied = r(), this.listenOn(window, "mapInfoChange", this.mapInfoChange), this.listenOn(window, "noLayersFound", this.noLayersFound), this.listenOn(window, "layerSelectionChange", this.layerSelectionChange), this.listenOn(window, "idsFound", this._idsFound), this.enableSingleExpand = !0, this.stackTools = !0, w(window);
  }
  static {
    this.properties = { appLayout: 1, appProxies: 1, defaultWebmapId: 1, defaultLayerId: 1, enableHome: 5, enableLegend: 5, enableLayerList: 5, enableFloorFilter: 5, enableFullscreen: 5, enableShare: 5, enableMapLayerPicker: 5, enableMapPicker: 5, enableSingleExpand: 5, enableSearch: 5, enableBasemap: 5, featureSelectionMode: 1, basemapConfig: 0, hide: 5, zoomToolsSize: 1, mapInfos: 0, mapWidgetsIndex: 9, mapWidgetsPosition: 1, mobileMapWidgetsPosition: 1, mapWidgetsSize: 1, mapView: 0, stackTools: 5, theme: 1, mapToolsOrder: 0, mobileToolsOrder: 0, isMapLayout: 5, shareIncludeEmbed: 5, shareIncludeSocial: 5, selectedFeaturesIds: 0, selectedLayer: 0, zoomToScale: 9, showOnlyUpdatableLayers: 5, isMobile: 5, mapInfo: 0, enableSelectionTool: 5, visibilityIcon: 1, pasteEnabled: 5, mapComponentId: 1, showCopyPasteActions: 5, _configLayerOrderDefined: 16, _translations: 16, _searchConfiguration: 16, _webMapInfo: 16, _toolInfos: 16, _filterActive: 16, _mapDivHeight: 16, _mapDivWidth: 16, _layerIds: 16 };
  }
  static {
    this.styles = C;
  }
  static {
    this.shadowRootOptions = L;
  }
  willUpdate(e) {
    if (e.has("appLayout") && this.appLayoutWatchHandler(), e.has("mapView") && this.mapViewWatchHandler(), e.has("mapInfo") && this.mapInfoWatchHandler(), e.has("selectedFeaturesIds") && this.selectedFeaturesIdsWatchHandler(), e.has("pasteEnabled") && this.hasUpdated) {
      const i = this._toolInfos.find((a) => a.icon === "paste-with-attribute");
      i && (i.disabled = !this.pasteEnabled);
    }
  }
  appLayoutWatchHandler() {
    this._updateShareUrl();
  }
  async mapInfoWatchHandler() {
    this._configLayerOrderDefined = "configLayerOrder" in (this.mapInfo?.layerOptions || {}), this._enabledLayerIds = M(this.mapInfo?.layerOptions?.layers || [], this.mapInfo?.layerOptions?.configLayerOrder);
  }
  async mapViewWatchHandler() {
    this.mapView && this._updateShareUrl();
  }
  async selectedFeaturesIdsWatchHandler() {
    this._updateShareUrl(), this._validateEnabledActions();
  }
  async resetFilter() {
    this._filterActive = !1, this._updateShareUrl();
  }
  async updateFilterState(e) {
    this._filterActive = e, this._updateShareUrl();
  }
  async updateLayer() {
    this._mapLayerPicker.value && this._mapLayerPicker.value.updateLayer();
  }
  async mapInfoChange(e) {
    this._selectedWebMapId = e.detail.id, await this._loadMap(e.detail);
  }
  noLayersFound() {
    this.selectedLayer = void 0, this.selectedFeaturesIds = [];
  }
  layerSelectionChange() {
    setTimeout(() => {
      this._initToolInfos();
    }, 50);
  }
  _idsFound(e) {
    this._layerIds = e.detail;
  }
  async load() {
    this._initToolInfos(), this._mapSizeObserver || (this._mapSizeObserver = new ResizeObserver(() => {
      this._mapDivWidth && this._mapDiv.value && (this._mapDivWidth = this._mapDiv.value.offsetWidth);
    }));
  }
  render() {
    const e = this.hide ? "visibility-hidden-1" : "", i = this.theme === "dark" ? "calcite-mode-dark" : "calcite-mode-light", a = "height-full", t = this.isMapLayout ? "" : "display-none", s = this._isValidWebMap ? "" : "hidden", h = this.isMobile ? "" : "hidden", o = this.enableMapPicker && this.mapInfos.length > 1, n = this.enableMapLayerPicker && this._layerIds.length > 1;
    return this._handleMapVisibility(), this._validateActiveActions(), l`<calcite-panel class="height-full width-full panel-header-override">${this._getMapLayerPicker()}${this._getHeaderActions()}<div slot=header-actions-end>${this.enableShare && this.isMapLayout ? this._getShare("share") : void 0}</div><calcite-progress class=${f(t)} value=0></calcite-progress><div class=${`${e} ${a}`}><div class="height-full" ${d(this._mapDiv)}><arcgis-map id=${this.mapComponentId ?? c} class="height-full" ${d(this._mapComponent)}></arcgis-map></div></div>${l`<map-tools style=${`visibility: ${s}`} .basemapConfig=${this.basemapConfig} class=${`box-shadow ${i} ${s}`} .configLayerOrderDefined=${this._configLayerOrderDefined} .defaultLayerId=${this.defaultLayerId} .enableBasemap=${this.enableBasemap} .enableFloorFilter=${this.enableFloorFilter} .enableFullscreen=${this.enableFullscreen} .enableHome=${this.enableHome} .enableLegend=${this.enableLegend} .enableLayerList=${this.enableLayerList} .enableSearch=${this.enableSearch} .enableSingleExpand=${this.enableSingleExpand} .enableSelectionTool=${this.enableSelectionTool} .isMobile=${this.isMobile} .parentComponentHeight=${this._mapDivHeight} .parentComponentWidth=${this._mapDivWidth} .zoomToolsSize=${this.zoomToolsSize} layout=horizontal .mapView=${this.mapView} .mapWidgetsSize=${this.mapWidgetsSize} .position=${this.mapWidgetsPosition} .selectedFeaturesIds=${this.selectedFeaturesIds} .selectedLayer=${this.selectedLayer} .searchConfiguration=${this._searchConfiguration} .stackTools=${this.stackTools} .toolOrder=${this.mapToolsOrder} .visibilityIcon=${this.visibilityIcon} ${d(this._mapTools)}></map-tools><map-tools style=${`visibility: ${h}`} class=${`box-shadow ${i} ${h}`} .configLayerOrderDefined=${this._configLayerOrderDefined} .defaultLayerId=${this.defaultLayerId} .enabledLayerIds=${this._enabledLayerIds} .enableMapLayerPicker=${n} .enableMapPicker=${o} .isMobile=${this.isMobile} .zoomToolsSize=${this.zoomToolsSize} layout=vertical .mapInfos=${this.mapInfos} .mapView=${this.mapView} .mapWidgetsSize=${this.mapWidgetsSize} .parentComponentHeight=${this._mapDivHeight} .position=${this.mobileMapWidgetsPosition} .selectedLayer=${this.selectedLayer} .selectedWebMapId=${this._selectedWebMapId} .showOnlyUpdatableLayers=${this.showOnlyUpdatableLayers} .stackTools=${this.stackTools} .toolOrder=${this.mobileToolsOrder} ${d(this._mobMapTools)}></map-tools>`}</calcite-panel>`;
  }
  updated() {
    this._mapDivHeight = this._mapDiv.value?.offsetHeight ?? 0, document.onclick = (e) => this._handleDocumentClick(e);
  }
  loaded() {
    this._mapDiv.value && this._mapSizeObserver?.observe(this._mapDiv.value), this._updateShareUrl();
  }
  async _loadMap(e) {
    const i = !this._defaultWebmapHonored && this.defaultWebmapId, a = this.mapInfos?.filter((o) => o.id === this.defaultWebmapId), t = JSON.stringify(e) !== JSON.stringify(this._webMapInfo);
    this._webMapInfo = i && a ? a[0] : !e?.id && this.mapInfos.length > 0 ? this.mapInfos[0] : e;
    const s = this._webMapInfo.id, h = i && e?.id === this.defaultWebmapId;
    if (this._loadedId !== s && !i || h) {
      const o = new T({
        portalItem: { id: s }
      });
      try {
        if (o && await o.load(), this.appProxies && o && await y(o, S, this.appProxies), this._mapComponent.value || await this.updateComplete, !this._mapComponent.value)
          throw new Error("Map component is not available.");
        this._mapComponent.value.map = o, this._mapComponent.value.resizeAlign = "center", await this._mapComponent.value.viewOnReady(), this.mapView = this._mapComponent.value.view, this._loadedId = s, this._searchConfiguration = this._webMapInfo.searchConfiguration, this.beforeMapChanged.emit(), this.mapView && await this.mapView.when(async () => {
          if (this.mapView) {
            this._mapDivWidth = this._mapDiv.value && this._mapDiv.value.offsetWidth, this._mapTools.value && this.mapView.ui.add(this._mapTools.value, { position: this.mapWidgetsPosition, index: this.mapWidgetsIndex }), this._mobMapTools.value && this.mapView.ui.add(this._mobMapTools.value, { position: this.mobileMapWidgetsPosition, index: this.mapWidgetsIndex }), this._defaultWebmapHonored = h ? !0 : this._defaultWebmapHonored, this._isValidWebMap = !0, this.mapChanged.emit({
              id: s,
              mapView: this.mapView,
              isValid: !0
            }), this.isMobile || document.getElementsByClassName("esri-zoom")[0]?.classList.remove("display-none");
            const n = o.initialViewProperties?.viewpoint?.clone();
            n && await this.mapView.goTo(n);
          }
        });
      } catch (n) {
        if (n.name !== "view:goto-interrupted") {
          console.error(n), this._loadedId = s, this._isValidWebMap = !1, this.mapChanged.emit({
            id: s,
            mapView: void 0,
            isValid: !1
          }), document.getElementsByClassName("esri-zoom")[0]?.classList.add("display-none");
          return;
        }
      }
    } else i ? (this._defaultWebmapHonored = !0, this._mapPicker.value && this._mapPicker.value.setMapByID(s)) : t && this.mapView && (this._searchConfiguration = this._webMapInfo.searchConfiguration, this.beforeMapChanged.emit(), this.mapChanged.emit({
      id: s,
      mapView: this.mapView,
      isValid: !0
    }));
    this._updateShareUrl();
  }
  _getMapLayerPicker() {
    const e = this.isMapLayout ? "header-actions-start" : "", i = this.mapInfos?.length > 1 ? "" : "display-none", a = this.isMapLayout ? "height-0" : "width-full", t = "display-flex", s = this.isMapLayout ? "" : "display-none";
    return l`${!this.isMobile && l`<div slot=${e ?? c}><map-picker class=${`${i} ${a}`} id=map-picker .isMapLayout=${this.isMapLayout} .mapInfos=${this.mapInfos} .selectedWebMapId=${this._selectedWebMapId} ${d(this._mapPicker)}></map-picker></div>` || ""}<div slot=header-actions-start class=${`mapView-header display-flex ${s}`} id=solutions-map-layer-picker-container><div class=${`border-end ${t}`}>${this.mapView && l`<map-layer-picker appearance=transparent .configLayerOrderDefined=${this._configLayerOrderDefined} .defaultLayerId=${this.defaultLayerId} display=inline-flex .enabledLayerIds=${this._enabledLayerIds} height=50 .isMobile=${this.isMobile} .mapView=${this.mapView} .showOnlyUpdatableLayers=${this.showOnlyUpdatableLayers} placeholder-icon=layers scale=l .selectedIds=${this.selectedLayer ? [this.selectedLayer.id] : []} show-single-layer-as-label show-tables show-tables-disabled type=dropdown ${d(this._mapLayerPicker)}></map-layer-picker>` || ""}</div></div>`;
  }
  _getHeaderActions() {
    return l`<div slot=header-content><calcite-action-bar class=${f("display-flex")} expand-disabled expanded id=${this._getId("bar") ?? c} layout=horizontal><calcite-action-group>${this.isMapLayout ? this._getTools() : void 0}</calcite-action-group></calcite-action-bar></div>`;
  }
  _getShare(e) {
    return l`<div class="share-action" id=${this._getId(e) ?? c}>${this.mapView && l`<instant-apps-social-share class="instant-app-share" .embed=${this.shareIncludeEmbed} flip-rtl popover-button-icon-scale=s scale=m share-button-color=neutral share-button-type=action .socialMedia=${this.shareIncludeSocial} .view=${this.mapView} ${d((i) => {
      i && (this._shareNode = i, this._updateShareUrl());
    })}></instant-apps-social-share>` || ""}${this._getToolTip("bottom", `map-${e}`, this._translations?.share)}</div>`;
  }
  _updateShareUrl() {
    const e = this._shareNode?.shareUrl;
    if (!e)
      return;
    const i = new URL(e);
    this._loadedId ? i.searchParams.set("webmap", this._loadedId) : i.searchParams.delete("webmap"), this.selectedLayer?.id ? i.searchParams.set("layer", this.selectedLayer.id) : i.searchParams.delete("layer"), this.selectedFeaturesIds?.length > 0 ? i.searchParams.set("oid", this.selectedFeaturesIds.join(",")) : i.searchParams.delete("oid"), this.appLayout && i.searchParams.set("applayout", this.appLayout), this._shareNode && (this._shareNode.autoUpdateShareUrl = !1, this._shareNode.shareUrl = i.href);
  }
  _initToolInfos() {
    const e = this.selectedFeaturesIds.length > 0, i = this.selectedFeaturesIds.length < 2 || this.selectedFeaturesIds.length > m, a = this.featureSelectionMode === "multiple" && this.selectedLayer?.capabilities?.operations.supportsUpdate, t = [];
    t.push({
      active: !1,
      icon: "filter",
      indicator: !1,
      label: this._translations.filters,
      func: () => {
        this._toggleFilter();
      },
      disabled: !1,
      toolTip: this._translations.filters
    }), t.push({
      active: !1,
      icon: "zoom-to-object",
      indicator: !1,
      label: this._translations.zoom,
      func: () => {
        this._zoom();
      },
      disabled: !e,
      toolTip: this._translations.zoom
    }), a && t.push({
      active: !1,
      icon: "pencil",
      indicator: !1,
      label: this._translations.editMultiple,
      func: () => this.editMultipleFeatures.emit(this.selectedFeaturesIds),
      disabled: i,
      toolTip: this._translations.editMultiple
    }), this.showCopyPasteActions && (t.push({
      active: !1,
      icon: "copy",
      indicator: !1,
      label: this._translations.copy,
      func: () => this.copyFeatures.emit({ featuresIds: this.selectedFeaturesIds, layerId: this.selectedLayer?.id }),
      disabled: !e,
      toolTip: this._translations.copy
    }), t.push({
      active: !1,
      icon: "paste-with-attribute",
      indicator: !1,
      label: this._translations.paste,
      func: () => this.pasteFeatures.emit(),
      disabled: !0,
      toolTip: this._translations.paste
    })), t.push({
      active: !1,
      icon: "refresh",
      indicator: !1,
      label: this._translations.refresh,
      func: () => this.selectedLayer?.refresh(),
      disabled: !1,
      toolTip: this._translations.refresh
    }), t.push({
      active: !1,
      icon: "erase",
      indicator: !1,
      label: this._translations.clearSelection,
      func: () => this.clearSelection.emit(),
      disabled: !e,
      toolTip: this._translations.clearSelection
    }), this._toolInfos = [...t];
  }
  _validateActiveActions() {
    const e = ["filter"];
    this._toolInfos?.forEach((i) => {
      i && e.indexOf(i.icon) > -1 && i.icon === "filter" && (i.indicator = this._filterActive);
    });
  }
  _handleMapVisibility() {
    if (this._mapDiv.value) {
      const e = this._mapDiv.value.getElementsByClassName("esri-view-surface")[0], i = this._mapDiv.value.getElementsByClassName("esri-attribution")[0];
      this._isValidWebMap ? (e?.classList.remove("hidden"), i?.classList.remove("hidden")) : (e?.classList.add("hidden"), i?.classList.add("hidden"));
    }
  }
  _validateEnabledActions() {
    const e = this.selectedFeaturesIds.length > 0, i = this.selectedFeaturesIds.length < 2 || this.selectedFeaturesIds.length > m, a = ["zoom-to-object", "pencil", "erase", "copy"];
    this._toolInfos?.forEach((t) => {
      t && a.indexOf(t.icon) > -1 && (t.disabled = t.icon === "pencil" ? i : !e, t.toolTip = t.icon === "pencil" ? this.selectedFeaturesIds.length > m ? this._translations.featureEditLimitNotice : this._translations.editMultiple : t.toolTip);
    });
  }
  _handleDocumentClick(e) {
    e.target.tagName !== "MAP-PICKER" && this._mapPicker.value && this._mapPicker.value.close();
  }
  async _zoom() {
    if (this.selectedLayer && this.mapView) {
      const e = await _(this.mapView, this.selectedLayer.id);
      e && await g(this.selectedFeaturesIds, e, this.mapView, !0, void 0, this.zoomToScale);
    }
  }
  async _toggleFilter() {
    this.toggleFilter.emit();
  }
  _getTools() {
    return this._toolInfos?.reduce((e, i) => (i && e.push(this._getAction(i.active, i.icon, i.indicator, i.label, i.func, i.disabled, i.loading, i.toolTip)), e), []);
  }
  _getToolTip(e, i, a) {
    return l`<calcite-tooltip .placement=${e} .referenceElement=${i}><span>${a}</span></calcite-tooltip>`;
  }
  _getAction(e, i, a, t, s, h, o, n) {
    const u = this.selectedLayer === void 0 ? !0 : h;
    return l`<calcite-action .active=${e} .disabled=${u} .icon=${i} .id=${`map-${i}`} .indicator=${a} .label=${t} .loading=${o} @click=${s} .text=${t} text-enabled></calcite-action>${this._getToolTip("auto", `map-${i}`, n)}`;
  }
  _getId(e) {
    return `solutions-action-${e}`;
  }
}
b("map-card", W);
export {
  W as MapCard
};
