/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { c as customElement } from "../../chunks/runtime.js";
import { b as BATCH_EDIT_LIMIT } from "../../chunks/interfaces.js";
import { joinAppProxies } from "templates-common-library/functionality/proxy";
import { c as getFeatureLayerView, e as goToSelection } from "../../chunks/mapViewUtils.js";
import { u as useT9n } from "../../chunks/useT9n.js";
import { css, html, nothing } from "lit";
import { createRef, ref } from "lit-html/directives/ref.js";
import { LitElement, createEvent, noShadowRoot, safeClassMap } from "@arcgis/lumina";
import { defineCustomElements } from "@arcgis/instant-apps-components/loader";
import { b as getEnabledLayerIds } from "../../chunks/helpers.js";
import config from "@arcgis/core/config";
import MapView from "@arcgis/core/views/MapView";
import WebMap from "@arcgis/core/WebMap";
const styles = css`@layer{
/** @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.
 */

: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;
  /* setting to 1 as 0 would cause the editor to not load in some cases */
}

.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 MapCard extends LitElement {
  constructor() {
    super();
    this.defaultWebmapId = "";
    this.defaultLayerId = "";
    this.enableHome = false;
    this.enableLegend = false;
    this.enableLayerList = true;
    this.enableFloorFilter = false;
    this.enableFullscreen = false;
    this.enableShare = false;
    this.enableMapLayerPicker = false;
    this.enableMapPicker = false;
    this.enableSingleExpand = false;
    this.enableSearch = false;
    this.enableBasemap = false;
    this.featureSelectionMode = "multiple";
    this.hide = false;
    this.zoomToolsSize = "m";
    this.mapInfos = [];
    this.mapWidgetsIndex = 0;
    this.mapWidgetsPosition = "top-leading";
    this.mobileMapWidgetsPosition = "top-right";
    this.mapWidgetsSize = "m";
    this.stackTools = false;
    this.mapToolsOrder = [];
    this.mobileToolsOrder = [];
    this.isMapLayout = false;
    this.shareIncludeEmbed = false;
    this.shareIncludeSocial = false;
    this.selectedFeaturesIds = [];
    this.showOnlyUpdatableLayers = false;
    this.isMobile = false;
    this.enableSelectionTool = false;
    this.visibilityIcon = "eyeball";
    this._configLayerOrderDefined = false;
    this._translations = useT9n({ name: "map-card", blocking: true });
    this._toolInfos = [];
    this._filterActive = false;
    this._layerIds = [];
    this._enabledLayerIds = [];
    this._defaultWebmapHonored = false;
    this._loadedId = "";
    this._mapDiv = createRef();
    this._mapPicker = createRef();
    this._mapTools = createRef();
    this._mobMapTools = createRef();
    this._mapLayerPicker = createRef();
    this._selectedWebMapId = "";
    this._isValidWebMap = true;
    this.mapChanged = createEvent();
    this.beforeMapChanged = createEvent();
    this.toggleFilter = createEvent();
    this.clearSelection = createEvent();
    this.editMultipleFeatures = createEvent();
    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 = true;
    this.stackTools = true;
    defineCustomElements(window);
  }
  static {
    this.properties = { appLayout: 1, appProxies: 1, defaultWebmapId: 1, defaultLayerId: 1, enableHome: [5, {}, { type: Boolean }], enableLegend: [5, {}, { type: Boolean }], enableLayerList: [5, {}, { type: Boolean }], enableFloorFilter: [5, {}, { type: Boolean }], enableFullscreen: [5, {}, { type: Boolean }], enableShare: [5, {}, { type: Boolean }], enableMapLayerPicker: [5, {}, { type: Boolean }], enableMapPicker: [5, {}, { type: Boolean }], enableSingleExpand: [5, {}, { type: Boolean }], enableSearch: [5, {}, { type: Boolean }], enableBasemap: [5, {}, { type: Boolean }], featureSelectionMode: 1, basemapConfig: [0, {}, { attribute: false }], hide: [5, {}, { type: Boolean }], zoomToolsSize: 1, mapInfos: [0, {}, { attribute: false }], mapWidgetsIndex: [9, {}, { type: Number }], mapWidgetsPosition: 1, mobileMapWidgetsPosition: 1, mapWidgetsSize: 1, mapView: [0, {}, { attribute: false }], stackTools: [5, {}, { type: Boolean }], theme: 1, mapToolsOrder: [0, {}, { attribute: false }], mobileToolsOrder: [0, {}, { attribute: false }], isMapLayout: [5, {}, { type: Boolean }], shareIncludeEmbed: [5, {}, { type: Boolean }], shareIncludeSocial: [5, {}, { type: Boolean }], selectedFeaturesIds: [0, {}, { attribute: false }], selectedLayer: [0, {}, { attribute: false }], zoomToScale: [9, {}, { type: Number }], showOnlyUpdatableLayers: [5, {}, { type: Boolean }], isMobile: [5, {}, { type: Boolean }], mapInfo: [0, {}, { attribute: false }], enableSelectionTool: [5, {}, { type: Boolean }], visibilityIcon: 1, _configLayerOrderDefined: [16, {}, { state: true }], _translations: [16, {}, { state: true }], _searchConfiguration: [16, {}, { state: true }], _webMapInfo: [16, {}, { state: true }], _toolInfos: [16, {}, { state: true }], _filterActive: [16, {}, { state: true }], _mapDivHeight: [16, {}, { state: true }], _mapDivWidth: [16, {}, { state: true }], _layerIds: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  static {
    this.shadowRootOptions = noShadowRoot;
  }
  willUpdate(changes) {
    if (changes.has("appLayout")) {
      this.appLayoutWatchHandler();
    }
    if (changes.has("mapView")) {
      void this.mapViewWatchHandler();
    }
    if (changes.has("mapInfo")) {
      void this.mapInfoWatchHandler();
    }
    if (changes.has("selectedFeaturesIds")) {
      void this.selectedFeaturesIdsWatchHandler();
    }
  }
  appLayoutWatchHandler() {
    this._updateShareUrl();
  }
  async mapInfoWatchHandler() {
    this._configLayerOrderDefined = "configLayerOrder" in (this.mapInfo?.layerOptions || {});
    this._enabledLayerIds = getEnabledLayerIds(this.mapInfo?.layerOptions?.layers || [], this.mapInfo?.layerOptions?.configLayerOrder);
  }
  async mapViewWatchHandler() {
    if (this.mapView) {
      this._updateShareUrl();
    }
  }
  async selectedFeaturesIdsWatchHandler() {
    this._updateShareUrl();
    this._validateEnabledActions();
  }
  async resetFilter() {
    this._filterActive = false;
    this._updateShareUrl();
  }
  async updateFilterState(active) {
    this._filterActive = active;
    this._updateShareUrl();
  }
  async updateLayer() {
    this._mapLayerPicker.value && void this._mapLayerPicker.value.updateLayer();
  }
  async mapInfoChange(_evt) {
    this._selectedWebMapId = _evt.detail.id;
    await this._loadMap(_evt.detail);
  }
  noLayersFound() {
    this.selectedLayer = void 0;
    this.selectedFeaturesIds = [];
  }
  layerSelectionChange() {
    setTimeout(() => {
      this._initToolInfos();
    }, 50);
  }
  _idsFound(_evt) {
    this._layerIds = _evt.detail;
  }
  async load() {
    this._initToolInfos();
    if (!this._mapSizeObserver) {
      this._mapSizeObserver = new ResizeObserver(() => {
        if (this._mapDivWidth && this._mapDiv.value) {
          this._mapDivWidth = this._mapDiv.value.offsetWidth;
        }
      });
    }
  }
  render() {
    const mapClass = this.hide ? "visibility-hidden-1" : "";
    const themeClass = this.theme === "dark" ? "calcite-mode-dark" : "calcite-mode-light";
    const mapHeightClass = "height-full";
    const progressClass = this.isMapLayout ? "" : "display-none";
    const defaultToolsVisibility = !this._isValidWebMap ? "hidden" : "";
    const mobileToolsVisibility = !this.isMobile ? "hidden" : "";
    const enableMapPicker = this.enableMapPicker && this.mapInfos.length > 1;
    const enableMapLayerPicker = this.enableMapLayerPicker && this._layerIds.length > 1;
    this._handleMapVisibility();
    this._validateActiveActions();
    return html`<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=${safeClassMap(progressClass)} value=0></calcite-progress><div class=${`${mapClass} ${mapHeightClass}`}><div class="height-full" ${ref(this._mapDiv)}></div></div>${html`<map-tools .basemapConfig=${this.basemapConfig} class=${`box-shadow ${themeClass} ${defaultToolsVisibility}`} .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} ${ref(this._mapTools)}></map-tools><map-tools class=${`box-shadow ${themeClass} ${mobileToolsVisibility}`} .defaultLayerId=${this.defaultLayerId} .enabledLayerIds=${this._enabledLayerIds} .enableMapLayerPicker=${enableMapLayerPicker} .enableMapPicker=${enableMapPicker} .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} ${ref(this._mobMapTools)}></map-tools>`}</calcite-panel>`;
  }
  updated() {
    this._mapDivHeight = this._mapDiv.value?.offsetHeight ?? 0;
    document.onclick = (e) => this._handleDocumentClick(e);
  }
  loaded() {
    if (this._mapDiv.value) {
      this._mapSizeObserver?.observe(this._mapDiv.value);
    }
    this._updateShareUrl();
  }
  async _loadMap(webMapInfo) {
    const loadDefaultMap = !this._defaultWebmapHonored && this.defaultWebmapId;
    const defaultMap = this.mapInfos?.filter((i) => i.id === this.defaultWebmapId);
    const mapConfigChanged = JSON.stringify(webMapInfo) !== JSON.stringify(this._webMapInfo);
    this._webMapInfo = loadDefaultMap && defaultMap ? defaultMap[0] : !webMapInfo?.id && this.mapInfos.length > 0 ? this.mapInfos[0] : webMapInfo;
    const id = this._webMapInfo.id;
    const isDefaultMap = loadDefaultMap && webMapInfo?.id === this.defaultWebmapId;
    if (this._loadedId !== id && !loadDefaultMap || isDefaultMap) {
      const webMap = new WebMap({
        portalItem: { id }
      });
      try {
        if (webMap) {
          await webMap.load();
        }
        if (this.appProxies && webMap) {
          await joinAppProxies(webMap, config, this.appProxies);
        }
        this.mapView = new MapView({
          container: this._mapDiv.value,
          map: webMap,
          resizeAlign: "center"
        });
        this._loadedId = id;
        this._searchConfiguration = this._webMapInfo.searchConfiguration;
        this.beforeMapChanged.emit();
        this.mapView && await this.mapView.when(() => {
          if (this.mapView) {
            this._mapDivWidth = this._mapDiv.value && this._mapDiv.value.offsetWidth;
            if (this._mapTools.value) {
              this.mapView.ui.add(this._mapTools.value, { position: this.mapWidgetsPosition, index: this.mapWidgetsIndex });
            }
            if (this._mobMapTools.value) {
              this.mapView.ui.add(this._mobMapTools.value, { position: this.mobileMapWidgetsPosition, index: this.mapWidgetsIndex });
            }
            this._defaultWebmapHonored = isDefaultMap ? true : this._defaultWebmapHonored;
            this._isValidWebMap = true;
            this.mapChanged.emit({
              id,
              mapView: this.mapView,
              isValid: true
            });
            if (!this.isMobile) {
              document.getElementsByClassName("esri-zoom")[0]?.classList.remove("display-none");
            }
          }
        });
      } catch (err) {
        console.error(err);
        this._loadedId = id;
        this._isValidWebMap = false;
        this.mapChanged.emit({
          id,
          mapView: void 0,
          isValid: false
        });
        document.getElementsByClassName("esri-zoom")[0]?.classList.add("display-none");
        return;
      }
    } else if (loadDefaultMap) {
      this._defaultWebmapHonored = true;
      if (this._mapPicker.value) {
        void this._mapPicker.value.setMapByID(id);
      }
    } else if (mapConfigChanged && this.mapView) {
      this._searchConfiguration = this._webMapInfo.searchConfiguration;
      this.beforeMapChanged.emit();
      this.mapChanged.emit({
        id,
        mapView: this.mapView,
        isValid: true
      });
    }
    this._updateShareUrl();
  }
  _getMapLayerPicker() {
    const slot = this.isMapLayout ? "header-actions-start" : "";
    const mapPickerClass = this.mapInfos?.length > 1 ? "" : "display-none";
    const width = this.isMapLayout ? "height-0" : "width-full";
    const containerClass = "display-flex";
    const headerElements = this.isMapLayout ? "" : "display-none";
    return html`${!this.isMobile && html`<div slot=${slot ?? nothing}><map-picker class=${`${mapPickerClass} ${width}`} id=map-picker .isMapLayout=${this.isMapLayout} .mapInfos=${this.mapInfos} .selectedWebMapId=${this._selectedWebMapId} ${ref(this._mapPicker)}></map-picker></div>` || ""}<div slot=header-actions-start class=${`mapView-header display-flex ${headerElements}`} id=solutions-map-layer-picker-container><div class=${`border-end ${containerClass}`}>${this.mapView && html`<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 ${ref(this._mapLayerPicker)}></map-layer-picker>` || ""}</div></div>`;
  }
  _getHeaderActions() {
    const containerClass = "display-flex";
    return html`<div slot=header-content><calcite-action-bar class=${safeClassMap(containerClass)} expand-disabled expanded id=${this._getId("bar") ?? nothing} layout=horizontal><calcite-action-group>${this.isMapLayout ? this._getActions() : void 0}</calcite-action-group></calcite-action-bar></div>`;
  }
  _getShare(icon) {
    return html`<div class="share-action" id=${this._getId(icon) ?? nothing}>${this.mapView && html`<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} ${ref((el) => {
      if (el) {
        this._shareNode = el;
        this._updateShareUrl();
      }
    })}></instant-apps-social-share>` || ""}${this._getToolTip("bottom", `map-${icon}`, this._translations?.share)}</div>`;
  }
  _updateShareUrl() {
    const url = this._shareNode?.shareUrl;
    if (!url) {
      return;
    }
    const urlObj = new URL(url);
    if (this._loadedId) {
      urlObj.searchParams.set("webmap", this._loadedId);
    } else {
      urlObj.searchParams.delete("webmap");
    }
    if (this.selectedLayer?.id) {
      urlObj.searchParams.set("layer", this.selectedLayer.id);
    } else {
      urlObj.searchParams.delete("layer");
    }
    if (this.selectedFeaturesIds?.length > 0) {
      urlObj.searchParams.set("oid", this.selectedFeaturesIds.join(","));
    } else {
      urlObj.searchParams.delete("oid");
    }
    if (this.appLayout) {
      urlObj.searchParams.set("applayout", this.appLayout);
    }
    if (this._shareNode) {
      this._shareNode.autoUpdateShareUrl = false;
      this._shareNode.shareUrl = urlObj.href;
    }
  }
  _initToolInfos() {
    const featuresSelected = this.selectedFeaturesIds.length > 0;
    const multipleEditsDisabled = this.selectedFeaturesIds.length < 2 || this.selectedFeaturesIds.length > BATCH_EDIT_LIMIT;
    const showMultipleEdits = this.featureSelectionMode === "multiple" && this.selectedLayer?.capabilities?.operations.supportsUpdate;
    const toolInfos = [];
    toolInfos.push({
      active: false,
      icon: "filter",
      indicator: false,
      label: this._translations.filters,
      func: () => void this._toggleFilter(),
      disabled: false,
      toolTip: this._translations.filters
    });
    toolInfos.push({
      active: false,
      icon: "zoom-to-object",
      indicator: false,
      label: this._translations.zoom,
      func: () => void this._zoom(),
      disabled: !featuresSelected,
      toolTip: this._translations.zoom
    });
    if (showMultipleEdits) {
      toolInfos.push({
        active: false,
        icon: "pencil",
        indicator: false,
        label: this._translations.editMultiple,
        func: () => this.editMultipleFeatures.emit(this.selectedFeaturesIds),
        disabled: multipleEditsDisabled,
        toolTip: this._translations.editMultiple
      });
    }
    toolInfos.push({
      active: false,
      icon: "refresh",
      indicator: false,
      label: this._translations.refresh,
      func: () => this.selectedLayer?.refresh(),
      disabled: false,
      toolTip: this._translations.refresh
    });
    toolInfos.push({
      active: false,
      icon: "erase",
      indicator: false,
      label: this._translations.clearSelection,
      func: () => this.clearSelection.emit(),
      disabled: !featuresSelected,
      toolTip: this._translations.clearSelection
    });
    this._toolInfos = [...toolInfos];
  }
  _validateActiveActions() {
    const activeDependant = ["filter"];
    this._toolInfos?.forEach((ti) => {
      if (ti && activeDependant.indexOf(ti.icon) > -1) {
        if (ti.icon === "filter") {
          ti.indicator = this._filterActive;
        }
      }
    });
  }
  _handleMapVisibility() {
    if (this._mapDiv.value) {
      const mapSurface = this._mapDiv.value.getElementsByClassName("esri-view-surface")[0];
      const attribution = this._mapDiv.value.getElementsByClassName("esri-attribution")[0];
      if (!this._isValidWebMap) {
        mapSurface?.classList.add("hidden");
        attribution?.classList.add("hidden");
      } else {
        mapSurface?.classList.remove("hidden");
        attribution?.classList.remove("hidden");
      }
    }
  }
  _validateEnabledActions() {
    const featuresSelected = this.selectedFeaturesIds.length > 0;
    const multipleEditsDisabled = this.selectedFeaturesIds.length < 2 || this.selectedFeaturesIds.length > BATCH_EDIT_LIMIT;
    const selectionDependant = ["zoom-to-object", "pencil", "erase"];
    this._toolInfos?.forEach((ti) => {
      if (ti && selectionDependant.indexOf(ti.icon) > -1) {
        ti.disabled = ti.icon === "pencil" ? multipleEditsDisabled : !featuresSelected;
        ti.toolTip = ti.icon === "pencil" ? this.selectedFeaturesIds.length > BATCH_EDIT_LIMIT ? this._translations.featureEditLimitNotice : this._translations.editMultiple : ti.toolTip;
      }
    });
  }
  _handleDocumentClick(e) {
    if (e.target.tagName !== "MAP-PICKER") {
      this._mapPicker.value && void this._mapPicker.value.close();
    }
  }
  async _zoom() {
    if (this.selectedLayer && this.mapView) {
      const selectedLayerView = await getFeatureLayerView(this.mapView, this.selectedLayer.id);
      if (selectedLayerView) {
        await goToSelection(this.selectedFeaturesIds, selectedLayerView, this.mapView, true, void 0, this.zoomToScale);
      }
    }
  }
  async _toggleFilter() {
    this.toggleFilter.emit();
  }
  _getActions() {
    return this._toolInfos?.reduce((prev, cur) => {
      if (cur) {
        prev.push(this._getAction(cur.active, cur.icon, cur.indicator, cur.label, cur.func, cur.disabled, cur.loading, cur.toolTip));
      }
      return prev;
    }, []);
  }
  _getToolTip(placement, referenceElement, text) {
    return html`<calcite-tooltip .placement=${placement} .referenceElement=${referenceElement}><span>${text}</span></calcite-tooltip>`;
  }
  _getAction(active, icon, indicator, label, func, disabled, loading, toolTip) {
    const _disabled = this.selectedLayer === void 0 ? true : disabled;
    return html`<calcite-action .active=${active} appearance=solid .disabled=${_disabled} .icon=${icon} .id=${`map-${icon}`} .indicator=${indicator} .label=${label} .loading=${loading} @click=${func} .text=${label} text-enabled></calcite-action>${this._getToolTip("auto", `map-${icon}`, toolTip)}`;
  }
  _getId(id) {
    return `solutions-action-${id}`;
  }
}
customElement("map-card", MapCard);
export {
  MapCard
};
