/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { c as customElement } from "../../chunks/runtime.js";
import { g as getLayerOrTable, a as getAllFeatureLayers, b as getAllTables, c as getFeatureLayerView, h as highlightFeatures, d as getMapLayerHash } from "../../chunks/mapViewUtils.js";
import { a as queryFeaturesByID } from "../../chunks/queryUtils.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 "@arcgis/instant-apps-components";
import { defineCustomElements } from "@arcgis/instant-apps-components/loader";
import * as reactiveUtils from "@arcgis/core/core/reactiveUtils";
import FeatureFilter from "@arcgis/core/layers/support/FeatureFilter";
import * as identify from "@arcgis/core/rest/identify";
import IdentifyParameters from "@arcgis/core/rest/support/IdentifyParameters";
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: 0px;
  --solutions-theme-foreground-color: var(--calcite-color-foreground-1);
}

.width-full {
  width: 100% !important;
}

.height-full {
  height: 100% !important;
}

.notice-msg {
  padding: 10px;
  width: calc(100% - 20px);
}

.progress-bar {
  padding: 12px;
}

.footer-top-button {
  padding-bottom: 7px;
}

.footer-button {
  height: 35px;
}

.feature-pagination {
  background-color: var(--calcite-color-foreground-1) !important;
  border-block-end: 1px solid var(--calcite-color-border-3);
  display: flex;
  justify-content: center;
  padding: 5px 0;
}

.pagination-count {
  color: var(--calcite-color-brand);
  border-bottom: 1px solid var(--calcite-color-brand);
  font-weight: bold;
}

.report-submitted-msg {
  position: absolute;
  z-index: 1000;
}

.share-node {
  display: flex;
}
}`;
class CrowdsourceReporter extends LitElement {
  constructor() {
    super();
    this.center = "";
    this.commentButtonText = "";
    this.commentSubmittedMessage = "";
    this.defaultWebmap = "";
    this.description = "";
    this.enableAnonymousAccess = false;
    this.enableAnonymousComments = false;
    this.enableComments = false;
    this.enableHome = true;
    this.enableLogin = false;
    this.enableNewReports = false;
    this.enableSearch = true;
    this.enableSnapping = false;
    this.enableZoom = true;
    this.isMobile = false;
    this.layerExpressions = [];
    this.layerId = "";
    this.level = "";
    this.loginTitle = "";
    this.mapInfos = [];
    this.objectId = "";
    this.reportButtonText = "";
    this.reportsHeader = "";
    this.reportSubmittedMessage = "";
    this.showComments = false;
    this.showUserImageInCommentsList = false;
    this.showFeatureSymbol = false;
    this.showMyReportsOnly = false;
    this.submitNewReportsMessage = "";
    this.theme = "light";
    this.floorLevel = "";
    this.showFullCommentTitle = true;
    this.filterByMapExtent = false;
    this.sortOption = "newest";
    this.reportingArea = false;
    this.reportingAreaLayer = "";
    this.reportingAreaMessage = "";
    this._featureCreationFailedErrorMsg = "";
    this._filterActive = false;
    this._flowItems = [];
    this._hasValidLayers = false;
    this._reportSubmitted = false;
    this._selectedLayerName = "";
    this._showSubmitCancelButton = false;
    this._showLoadingIndicator = false;
    this._sidePanelCollapsed = false;
    this._translations = useT9n({ name: "crowdsource-reporter", blocking: true });
    this._updatedProgressBarStatus = 25;
    this._updatedSortOption = "newest";
    this._commentSubmitted = false;
    this._addingCommentFailed = false;
    this._filterOpen = false;
    this._showNextButton = false;
    this._submitNextButtonDisabled = false;
    this._createFeature = createRef();
    this._currentFeatureId = "";
    this._editableLayerIds = [];
    this._featureDetails = createRef();
    this._featureList = createRef();
    this._selectedRelatedFeature = [];
    this._layerList = createRef();
    this._createRelatedFeature = createRef();
    this._layers = [];
    this._mapImageryLayersId = [];
    this._selectedFeature = [];
    this._selectedFeatureIndex = 0;
    this._selectedLayerId = "";
    this._shareNode = createRef();
    this._urlParamsLoaded = false;
    this._validLayers = [];
    this._nonVisibleValidLayers = [];
    this._showFullPanel = false;
    this._floorExpression = "";
    this._formElements = [];
    this._prevSelectedLayerId = "";
    this._t9nLayerExpressions = [];
    this._reportSubmittedAlertNode = createRef();
    this._commentSubmittedAlertNode = createRef();
    this._sortPopoverNode = createRef();
    this.togglePanel = createEvent();
    defineCustomElements(window);
  }
  static {
    this.properties = { center: 1, commentButtonText: 1, commentSubmittedMessage: 1, defaultWebmap: 1, description: 1, enableAnonymousAccess: [5, {}, { type: Boolean }], enableAnonymousComments: [5, {}, { type: Boolean }], enableComments: [5, {}, { type: Boolean }], enableHome: [5, {}, { type: Boolean }], enableLogin: [5, {}, { type: Boolean }], enableNewReports: [5, {}, { type: Boolean }], enableSearch: [5, {}, { type: Boolean }], enableSnapping: [5, {}, { type: Boolean }], enableZoom: [5, {}, { type: Boolean }], isMobile: [5, {}, { type: Boolean }], layerExpressions: [0, {}, { attribute: false }], layerId: 1, level: 1, loginTitle: 1, mapInfos: [0, {}, { attribute: false }], mapView: [0, {}, { attribute: false }], objectId: 1, reportButtonText: 1, reportingOptions: [0, {}, { attribute: false }], reportsHeader: 1, reportSubmittedMessage: 1, searchConfiguration: [0, {}, { attribute: false }], showComments: [5, {}, { type: Boolean }], showUserImageInCommentsList: [5, {}, { type: Boolean }], showFeatureSymbol: [5, {}, { type: Boolean }], showMyReportsOnly: [5, {}, { type: Boolean }], submitNewReportsMessage: 1, theme: 1, zoomToScale: [9, {}, { type: Number }], floorLevel: 1, showFullCommentTitle: [5, {}, { type: Boolean }], filterByMapExtent: [5, {}, { type: Boolean }], sortOption: 1, reportingArea: [5, {}, { type: Boolean }], reportingAreaLayer: 1, reportingAreaMessage: 1, _featureCreationFailedErrorMsg: [16, {}, { state: true }], _filterActive: [16, {}, { state: true }], _flowItems: [16, {}, { state: true }], _hasValidLayers: [16, {}, { state: true }], _mapInfo: [16, {}, { state: true }], _reportSubmitted: [16, {}, { state: true }], _selectedLayerName: [16, {}, { state: true }], _showSubmitCancelButton: [16, {}, { state: true }], _showLoadingIndicator: [16, {}, { state: true }], _sidePanelCollapsed: [16, {}, { state: true }], _translations: [16, {}, { state: true }], _updatedProgressBarStatus: [16, {}, { state: true }], _updatedSorting: [16, {}, { state: true }], _updatedSortOption: [16, {}, { state: true }], _commentSubmitted: [16, {}, { state: true }], _addingCommentFailed: [16, {}, { state: true }], _filterOpen: [16, {}, { state: true }], _showNextButton: [16, {}, { state: true }], _submitNextButtonDisabled: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  static {
    this.shadowRootOptions = noShadowRoot;
  }
  willUpdate(changes) {
    if (changes.has("isMobile")) {
      void this.isMobileWatchHandler(this.isMobile);
    }
    if (changes.has("mapView") && this.hasUpdated) {
      void this.mapViewWatchHandler();
    }
    if (changes.has("floorLevel")) {
      void this.floorLevelWatchHandler();
    }
    if (changes.has("reportingAreaLayer") || changes.has("reportingArea") && this.hasUpdated) {
      setTimeout(() => {
        if (this._createFeature.value) {
          void this._createFeature.value.refresh(this.floorLevel);
        }
      }, 50);
    }
    if (changes.has("showMyReportsOnly") && (this.hasUpdated || this.showMyReportsOnly !== false)) {
      void this.showMyReportsOnlyWatchHandler();
    }
    if (changes.has("sortOption") && (this.hasUpdated || this.sortOption !== "newest")) {
      void this.sortOptionWatchHandler();
    }
    if (changes.has("filterByMapExtent") && (this.hasUpdated || this.filterByMapExtent !== false)) {
      this.filterByMapExtentChangeWatchHandler();
    }
    if (changes.has("layerExpressions") && (this.hasUpdated || this.layerExpressions?.length > 0)) {
      void this.layerExpressionsWatchHandler();
    }
    if (changes.has("showFeatureSymbol") && (this.hasUpdated || this.showFeatureSymbol !== false)) {
      void this.showFeatureSymbolWatchHandler();
    }
    if (this._flowItems.includes("filter-panel") || this._filterOpen) {
      void this._filterList?.updateInitDefExpressions({ initDefExpressions: this._initDefExpressions });
    }
  }
  async isMobileWatchHandler(isMobile) {
    this.updatePanelState(false, this._showFullPanel);
    if (isMobile && this._flowItems[this._flowItems.length - 1] === "filter-panel") {
      await this.backFromFilterPanel();
      this._filterOpen = true;
    } else if (!isMobile && this._filterOpen) {
      await this._closeFilter();
      this._flowItems = [...this._flowItems, "filter-panel"];
    }
  }
  async mapViewWatchHandler() {
    await this.mapView?.when(async () => {
      this.setInitExpressions();
      await this.setMapView();
    });
  }
  async floorLevelWatchHandler() {
    if (this._editableLayerIds) {
      for (const layerId of this._editableLayerIds) {
        const layer = this.mapView && await getLayerOrTable(this.mapView, layerId);
        if (layer && layer.floorInfo?.floorField) {
          this._updateFloorDefinitionExpression(layer);
        }
      }
    }
    if (this._flowItems[this._flowItems.length - 1] === "layer-list" && this._layerList.value) {
      await this._layerList.value.refresh();
    }
    if (this._featureList.value) {
      void this._featureList.value.refresh();
    }
    if (this._createFeature.value) {
      void this._createFeature.value.refresh(this.floorLevel);
    }
  }
  async showMyReportsOnlyWatchHandler() {
    if (this._editableLayerIds) {
      await this._updateFeatures();
      this.refreshLists();
    }
  }
  async sortOptionWatchHandler() {
    this.updateSortingOptions();
  }
  filterByMapExtentChangeWatchHandler() {
    this.refreshLists();
  }
  async layerExpressionsWatchHandler() {
    await this.resetFilterList();
    await this.handleSelectedLayersFilter();
    await this._featureList.value?.refresh();
  }
  async showFeatureSymbolWatchHandler() {
    await this._featureList.value?.refresh();
  }
  async updateLayerExpressionsT9n(t9nLayerExpressions) {
    this._t9nLayerExpressions = t9nLayerExpressions ? t9nLayerExpressions : this.layerExpressions;
    if (this._filterList != null) {
      await this._filterList.handleUpdatingT9nData(this._t9nLayerExpressions);
    } else if (this._currentLayerExpressions != null) {
      const currentLayerExpressions = structuredClone(this._currentLayerExpressions);
      this.handleLayerExpressionsT9n(currentLayerExpressions, this._t9nLayerExpressions);
      this._currentLayerExpressions = currentLayerExpressions;
    }
    return Promise.resolve();
  }
  async load() {
    this._urlParamsLoaded = false;
    await this.mapView?.when(async () => {
      this._layers = this.reportingOptions ? Object.keys(this.reportingOptions).filter((layerId) => {
        const reportingOption = layerId && this.reportingOptions && this.reportingOptions[layerId];
        return reportingOption && reportingOption.visible;
      }) : [];
      this.setInitExpressions();
      await this.setMapView();
    });
  }
  render() {
    const themeClass = this.theme === "dark" ? "calcite-mode-dark" : "calcite-mode-light";
    return html`${this._reportSubmitted && html`<calcite-alert auto-close class=${`${themeClass} report-submitted-msg`} icon=check-circle kind=success label @calciteAlertClose=${() => {
      this._reportSubmitted = false;
    }} open placement=top><div slot=message .innerHTML=${(this.reportSubmittedMessage || this._translations.submitMsg) ?? ""} ${ref(this._reportSubmittedAlertNode)}></div></calcite-alert>` || ""}${this._featureCreationFailedErrorMsg && html`<calcite-alert auto-close class=${safeClassMap(themeClass)} icon=x-octagon kind=danger label @calciteAlertClose=${() => {
      this._featureCreationFailedErrorMsg = "";
    }} open placement=top><div slot=title>${this._translations.error}</div><div slot=message>${this._featureCreationFailedErrorMsg}</div></calcite-alert>` || ""}${this._commentSubmitted && html`<calcite-alert auto-close class=${`report-submitted ${themeClass}`} icon=check-circle kind=success label @calciteAlertClose=${() => {
      this._commentSubmitted = false;
    }} open placement=top><div slot=message .innerHTML=${(this.commentSubmittedMessage || this._translations.commentSubmittedMsg) ?? ""} ${ref(this._commentSubmittedAlertNode)}></div></calcite-alert>` || ""}${this._addingCommentFailed && html`<calcite-alert auto-close class=${safeClassMap(themeClass)} icon=x-octagon kind=danger label @calciteAlertClose=${() => {
      this._addingCommentFailed = false;
    }} open placement=top><div slot=title>${this._translations.error}</div><div slot=message>${this._translations.addingCommentFailedMsg}</div></calcite-alert>` || ""}<div><calcite-shell content-behind>${this._getReporter()}</calcite-shell></div>${this.isMobile && this.filterModal() || ""}`;
  }
  updated() {
    this._adjustAlertStyles();
  }
  async setSelectedLayer(layerId, layerName) {
    this._selectedLayerId = layerId;
    this._selectedLayer = this.mapView && await getLayerOrTable(this.mapView, layerId);
    this._selectedLayerName = layerName;
    this._validLayers.forEach((layer) => {
      const nonVisibileValidLayer = this._nonVisibleValidLayers.find((l) => l.id === layer.id);
      if (!nonVisibileValidLayer) {
        layer.set("visible", !layerId || layer.id === layerId);
      }
    });
  }
  _getLayersConfig(layerId) {
    return this.reportingOptions && this.reportingOptions[layerId] ? this.reportingOptions[layerId] : null;
  }
  _getReporter() {
    const renderLists = [];
    this._flowItems.forEach((item) => {
      switch (item) {
        case "layer-list":
          renderLists.push(this.getLayerListFlowItem());
          break;
        case "feature-list":
          renderLists.push(this.getFeatureListFlowItem(this._selectedLayerId, this._selectedLayerName));
          break;
        case "filter-panel":
          renderLists.push(this.getFilterPanel());
          break;
        case "feature-details":
          renderLists.push(this.getFeatureDetailsFlowItem());
          break;
        case "reporting-layer-list":
          renderLists.push(this.getChooseCategoryFlowItem());
          break;
        case "feature-create":
          renderLists.push(this.getFeatureCreateFlowItem());
          break;
        case "comment-details":
          renderLists.push(this.getCommentDetailsFlowItem());
          break;
        case "add-comment":
          renderLists.push(this.getAddCommentFlowItem());
          break;
      }
    });
    const themeClass = this.theme === "dark" ? "calcite-mode-dark" : "calcite-mode-light";
    return html`<calcite-panel class=${`width-full ${themeClass}`}>${this.mapView ? html`<calcite-flow>${renderLists?.length > 0 && renderLists || ""}</calcite-flow>` : html`<calcite-loader label scale=m></calcite-loader>`}</calcite-panel>`;
  }
  filterModal() {
    const currentLayersExpressions = this.layerExpressions ? this.layerExpressions.filter((exp) => exp.id === this._selectedLayerId) : [];
    return currentLayersExpressions.length > 0 && html`<calcite-dialog aria-labelledby=modal-title class="modal" kind=brand @calciteDialogClose=${() => void this._closeFilter()} .open=${this._filterOpen} width=s><div class="display-flex align-center" id=modal-title slot=header>${this._translations.filterLayerTitle.replace("{{title}}", this._selectedLayerName)}</div><div slot=content>${this.mapView && html`<instant-apps-filter-list close-btn .closeBtnOnClick=${() => void this._closeFilter()} combobox-overlay-positioning=fixed .layerExpressions=${this._currentLayerExpressions} @filterListReset=${() => {
      this._filterActive = false;
      this._featureList.value && void this._featureList.value.refresh();
    }} @filterUpdate=${() => {
      if (this._filterList?.filterCount !== void 0) {
        void this._handleFilterUpdate(this._filterList?.filterCount > 0);
      }
    }} .view=${this.mapView} ${ref(this._setFilterList)}></instant-apps-filter-list>` || ""}</div></calcite-dialog>` || "";
  }
  _setFilterList(element) {
    this._filterList = element;
    if (element) {
      element.autoUpdateUrl = false;
      element.resetBtn = this.isMobile;
      element.resetFiltersOnDisconnect = false;
      element.zoomBtn = false;
    }
  }
  _adjustAlertStyles() {
    if (this.reportSubmittedMessage && this._reportSubmittedAlertNode.value?.children[0]) {
      this._reportSubmittedAlertNode.value.children[0].style.margin = "0px";
    }
    if (this.commentSubmittedMessage && this._commentSubmittedAlertNode.value?.children[0]) {
      this._commentSubmittedAlertNode.value.children[0].style.margin = "0px";
    }
  }
  _toggleFilter() {
    this._filterOpen = !this._filterOpen;
  }
  async _closeFilter() {
    this._filterOpen = false;
    if (this._filterList != null) {
      this._currentLayerExpressions = await this._filterList.getCurrentLayerExpressions();
    }
  }
  async sortOptionClick(sortField, sortOrder, sortOption) {
    this._updatedSorting = {
      field: sortField,
      order: sortOrder
    };
    this._updatedSortOption = sortOption;
    if (this._sortPopoverNode.value) {
      this._sortPopoverNode.value.open = false;
    }
  }
  _toggleSort() {
    const canSortByVotes = this.reportingOptions && this.reportingOptions[this._selectedLayerId] && this.reportingOptions[this._selectedLayerId].like && this.reportingOptions[this._selectedLayerId].likeField;
    return html`<calcite-popover auto-close label offset-distance=0 .placement=${this.isMobile ? "leading-start" : "bottom-start"} pointer-disabled reference-element=sort-popover ${ref(this._sortPopoverNode)}><calcite-list label selection-mode=single-persist><calcite-list-item .label=${this._translations.sortNewest} @calciteListItemSelect=${() => {
      if (this._selectedLayer) {
        void this.sortOptionClick(this._selectedLayer.objectIdField, "desc", "newest");
      }
    }} .selected=${this._updatedSortOption === "newest"} value=newest></calcite-list-item><calcite-list-item .label=${this._translations.sortOldest} @calciteListItemSelect=${() => {
      if (this._selectedLayer) {
        void this.sortOptionClick(this._selectedLayer.objectIdField, "asc", "oldest");
      }
    }} .selected=${this._updatedSortOption === "oldest"} value=oldest></calcite-list-item>${canSortByVotes && html`<calcite-list-item .label=${this._translations.sortHighestVoted} @calciteListItemSelect=${() => {
      const likeField = this.reportingOptions && this.reportingOptions[this._selectedLayerId].likeField;
      if (likeField !== void 0) {
        void this.sortOptionClick(likeField, "desc", "highestVoted");
      }
    }} .selected=${this._updatedSortOption === "highestVoted"} value=highestVoted></calcite-list-item><calcite-list-item .label=${this._translations.sortLowestVoted} @calciteListItemSelect=${() => {
      const likeField = this.reportingOptions && this.reportingOptions[this._selectedLayerId].likeField;
      if (likeField) {
        void this.sortOptionClick(likeField, "asc", "lowestVoted");
      }
    }} .selected=${this._updatedSortOption === "lowestVoted"} value=lowestVoted></calcite-list-item>` || ""}</calcite-list></calcite-popover>`;
  }
  async _handleFilterListReset() {
    this._filterActive = false;
  }
  async _handleFilterUpdate(active) {
    this._showLoadingIndicator = true;
    this._filterActive = active;
    this._featureList.value && await this._featureList.value.refresh();
    this._showLoadingIndicator = false;
  }
  getLayerListFlowItem() {
    return html`<calcite-flow-item .collapsed=${this.isMobile && this._sidePanelCollapsed} .heading=${this.reportsHeader} .loading=${this._showLoadingIndicator} .selected=${this._flowItems[this._flowItems.length - 1] === "layer-list"}>${this.isMobile && this.getActionToExpandCollapsePanel() || ""}${this._hasValidLayers && this.enableNewReports && html`<calcite-button appearance=solid @click=${this.navigateToChooseCategory} slot=footer width=full>${this.reportButtonText ? this.reportButtonText : this._translations.createReportButtonText}</calcite-button>` || ""}<calcite-panel><layer-list .applyLayerViewFilter=${this.showMyReportsOnly} class="height-full" .filterByMapExtent=${this.filterByMapExtent} .layers=${this._editableLayerIds?.length > 0 ? this._editableLayerIds : this._layers} .mapView=${this.mapView} @layerSelect=${this.displayFeaturesList} @layersListLoaded=${this.layerListLoaded} show-feature-count show-next-icon ${ref(this._layerList)}></layer-list></calcite-panel></calcite-flow-item>`;
  }
  getChooseCategoryFlowItem() {
    const onlyReportingLayers = this.reportingOptions ? Object.keys(this.reportingOptions).filter((layerId) => {
      return this.reportingOptions && this.reportingOptions[layerId].visible && this.reportingOptions[layerId].reporting && this._layerItemsHash && this._layerItemsHash[layerId] && this._layerItemsHash[layerId].supportsAdd;
    }) : [];
    return html`<calcite-flow-item .collapsed=${this.isMobile && this._sidePanelCollapsed} .heading=${this.reportButtonText ? this.reportButtonText : this._translations.createReportButtonText} @calciteFlowItemBack=${this.backFromSelectedPanel} .selected=${this._flowItems[this._flowItems.length - 1] === "reporting-layer-list"}><calcite-panel><div class="progress-bar"><calcite-progress type=determinate .value=${this._updatedProgressBarStatus}></calcite-progress></div><calcite-notice class="notice-msg" icon=lightbulb kind=success open><div slot=message>${this._translations.chooseCategoryMsg}</div></calcite-notice><layer-list class="height-full" .layers=${onlyReportingLayers} .mapView=${this.mapView} @layerSelect=${this.navigateToCreateFeature}></layer-list></calcite-panel></calcite-flow-item>`;
  }
  getFeatureCreateFlowItem() {
    return html`<calcite-flow-item .collapsed=${this.isMobile && this._sidePanelCollapsed} .heading=${this._selectedLayerName} @calciteFlowItemBack=${this.backFromCreateFeaturePanel} .selected=${this._flowItems[this._flowItems.length - 1] === "feature-create"}>${this._showSubmitCancelButton && html`<div class=width-full slot=footer><calcite-button appearance=solid class="footer-top-button footer-button" .disabled=${this._submitNextButtonDisabled} @click=${this._showNextButton ? this.onNextButtonClick.bind(this) : this.onCreateFeatureSubmitButtonClick.bind(this)} width=full>${this._showNextButton ? this._translations.next : this._translations.submit}</calcite-button><calcite-button appearance=outline class=footer-button @click=${this.backFromCreateFeaturePanel} width=full>${this._translations.cancel}</calcite-button></div>` || ""}<calcite-panel><div class="progress-bar"><calcite-progress type=determinate .value=${this._updatedProgressBarStatus}></calcite-progress></div><create-feature customize-submit enable-search .enableSnapping=${this.enableSnapping} .floorLevel=${this.floorLevel} .formElements=${this._formElements.find((elm) => elm.id === this._selectedLayerId)} .reportingAreaLayer=${this.reportingAreaLayer} .isMobile=${this.isMobile} .mapView=${this.mapView} @drawComplete=${this.onFormReady} @editingLocation=${this.editingLocation} @editingAttachment=${this.showSubmitCancelButton} @fail=${this.createFeatureFailed} @modeChanged=${this.backFromCreateFeaturePanel} @progressStatus=${this.updatedProgressStatus} @success=${this.onReportSubmitted} .searchConfiguration=${this.searchConfiguration} .selectedLayerId=${this._selectedLayerId} .reportingArea=${this.reportingArea} .reportingAreaMessage=${this.reportingAreaMessage} .submitNewReportsMessage=${this.submitNewReportsMessage} update-map-position ${ref(this._createFeature)}></create-feature></calcite-panel></calcite-flow-item>`;
  }
  updatedProgressStatus(_evt) {
    this._updatedProgressBarStatus = _evt.detail;
  }
  onFormReady(_evt) {
    this._submitNextButtonDisabled = _evt.detail;
    this._showSubmitCancelButton = true;
  }
  editingLocation() {
    this._showNextButton = true;
  }
  showSubmitCancelButton(_evt) {
    this._showSubmitCancelButton = !_evt.detail;
  }
  onCreateFeatureSubmitButtonClick() {
    if (this._createFeature.value) {
      this._showNextButton = false;
      void this._createFeature.value.submit();
    }
  }
  backFromCreateFeaturePanel() {
    if (this._createFeature.value) {
      this._showSubmitCancelButton = false;
      this._showNextButton = false;
      void this.updateNonVisibleLayersOnMap(false);
    }
    this.backFromSelectedPanel();
  }
  onNextButtonClick() {
    if (this._createFeature.value) {
      this._showNextButton = false;
      this._showSubmitCancelButton = true;
      void this._createFeature.value.showForm();
    }
  }
  onCreateRelatedFeatureSubmitButtonClick() {
    if (this._createRelatedFeature.value) {
      void this._createRelatedFeature.value.submit();
    }
  }
  backFromCreateRelatedFeaturePanel() {
    if (this._createRelatedFeature.value) {
      this._showSubmitCancelButton = false;
    }
    this.backFromSelectedPanel();
  }
  createFeatureFailed(_evt) {
    console.error(_evt.detail);
    this._featureCreationFailedErrorMsg = _evt.detail.message;
  }
  async onReportSubmitted() {
    this._showSubmitCancelButton = false;
    void this.updateNonVisibleLayersOnMap(false);
    await this.navigateToHomePage();
    this._reportSubmitted = true;
    this._updatedProgressBarStatus = 25;
    if (this._showFullPanel) {
      this.updatePanelState(this._sidePanelCollapsed, false);
    }
  }
  addCommentFailed(_evt) {
    console.error(_evt.detail);
    this._addingCommentFailed = true;
  }
  async onCommentSubmitted() {
    this._commentSubmitted = true;
    this.backFromCreateRelatedFeaturePanel();
    this._showLoadingIndicator = true;
    this._featureDetails.value && await this._featureDetails.value.refresh(this._currentFeature);
    setTimeout(() => {
      this._showLoadingIndicator = false;
    }, 300);
  }
  async navigateToHomePage() {
    await this.setSelectedFeatures([]);
    if (this._layerList.value) {
      await this._layerList.value.refresh();
    }
    if (this._editableLayerIds.length === 1) {
      this._featureList.value && await this._featureList.value.refresh();
      this._flowItems = ["feature-list"];
    } else {
      this._flowItems = ["layer-list"];
    }
  }
  async navigateToCreateFeature(_evt) {
    if (_evt.detail.layerId && _evt.detail.layerName) {
      await this.setSelectedLayer(_evt.detail.layerId, _evt.detail.layerName);
    }
    void this.updateNonVisibleLayersOnMap(true);
    this._getFormElements();
    this._showSubmitCancelButton = false;
    this._showNextButton = false;
    this.updatePanelState(false, true);
    this._flowItems = [...this._flowItems, "feature-create"];
  }
  navigateToChooseCategory() {
    this.updatePanelState(false, true);
    this._flowItems = [...this._flowItems, "reporting-layer-list"];
  }
  updateNonVisibleLayersOnMap(visible) {
    const isNonVisibleValidLayerSelected = this._nonVisibleValidLayers.find((layer) => layer.id === this._selectedLayerId);
    if (isNonVisibleValidLayerSelected && this._selectedLayer) {
      this._selectedLayer.set("visible", visible);
    }
  }
  async layerListLoaded(_evt) {
    const presentOnLayerListPanel = this._layerList.value && this._flowItems[this._flowItems.length - 1] === "layer-list" || this._flowItems[0] === "feature-list";
    if (presentOnLayerListPanel) {
      const layersListed = _evt.detail;
      const allMapLayers = this.mapView && await getAllFeatureLayers(this.mapView);
      const reportingEnabledLayerIds = [];
      this._validLayers = [];
      this._nonVisibleValidLayers = [];
      allMapLayers?.forEach((eachLayer) => {
        if (layersListed.includes(eachLayer.id)) {
          this._validLayers.push(eachLayer);
          if (!eachLayer.visible) {
            this._nonVisibleValidLayers.push(eachLayer);
          }
          if (this._getLayersConfig(eachLayer.id)?.reporting && this._layerItemsHash && this._layerItemsHash[eachLayer.id] && this._layerItemsHash[eachLayer.id].supportsAdd) {
            reportingEnabledLayerIds.push(eachLayer.id);
          }
        }
      });
      this.handleMapClick();
      this._hasValidLayers = reportingEnabledLayerIds.length > 0;
      if (!this._urlParamsLoaded && this._editableLayerIds.length > 1) {
        if (this.layerId && this.objectId) {
          const layer = this.mapView && await getLayerOrTable(this.mapView, this.layerId);
          if (layer) {
            await this.displayFeaturesList({
              detail: {
                layerId: layer.id,
                layerName: layer.title
              }
            });
          }
          this._urlParamsLoaded = true;
          await this.loadFeatureFromURLParams();
        }
      }
    }
  }
  async displayFeaturesList(_evt) {
    this._showLoadingIndicator = true;
    await this.setSelectedLayer(_evt.detail.layerId, _evt.detail.layerName);
    void this.updateSortingOptions();
    void this.handleSelectedLayersFilter();
    this._flowItems = [...this._flowItems, "feature-list"];
    this._prevSelectedLayerId = this._selectedLayerId;
    this._showLoadingIndicator = false;
  }
  updateSortingOptions() {
    const sortingOption = this.sortOption === "" ? "newest" : this.sortOption;
    const sortOrder = sortingOption === "oldest" || sortingOption === "lowestVoted" ? "asc" : "desc";
    const likeField = this.reportingOptions?.[this._selectedLayerId]?.like ? this.reportingOptions?.[this._selectedLayerId]?.likeField : "";
    const sortField = this._selectedLayer && (sortingOption === "newest" || sortingOption === "oldest") ? this._selectedLayer?.objectIdField : likeField;
    this._updatedSorting = {
      field: sortField || "",
      order: sortOrder
    };
    this._updatedSortOption = !likeField && (sortingOption === "highestVoted" || sortingOption === "lowestVoted") ? "newest" : sortingOption;
  }
  async backFromFilterPanel() {
    if (this._filterList != null) {
      this._currentLayerExpressions = await this._filterList.getCurrentLayerExpressions();
    }
    this._featureList.value && await this._featureList.value.refresh();
    this.backFromSelectedPanel();
  }
  backFromSelectedPanel() {
    this._updatedProgressBarStatus = 25;
    const updatedFlowItems = [...this._flowItems];
    if (!(updatedFlowItems[updatedFlowItems.length - 1] === "comment-details" || updatedFlowItems[updatedFlowItems.length - 1] === "add-comment")) {
      this.clearHighlights();
    }
    if (updatedFlowItems[updatedFlowItems.length - 1] === "reporting-layer-list" || updatedFlowItems[updatedFlowItems.length - 1] === "feature-create" && (updatedFlowItems[0] === "feature-list" || updatedFlowItems[updatedFlowItems.length - 2] === "feature-list")) {
      this.updatePanelState(this._sidePanelCollapsed, false);
    }
    updatedFlowItems.pop();
    if (updatedFlowItems.length === 1 && updatedFlowItems[0] === "layer-list") {
      void this.navigateToHomePage();
      return;
    }
    this._flowItems = [...updatedFlowItems];
  }
  toggleSidePanel() {
    this._sidePanelCollapsed = !this._sidePanelCollapsed;
    this.togglePanel.emit({ panelState: this._sidePanelCollapsed, isFormOpen: this._showFullPanel });
  }
  updatePanelState(sidePanelCollapsed, showFullPanel) {
    this._sidePanelCollapsed = sidePanelCollapsed;
    this._showFullPanel = showFullPanel;
    this.togglePanel.emit({ panelState: this._sidePanelCollapsed, isFormOpen: this._showFullPanel });
  }
  async onFeatureSelectFromList(_evt) {
    await this.setSelectedFeatures([_evt.detail]);
    this._flowItems = [...this._flowItems, "feature-details"];
  }
  async getRelatedTable() {
    const selectedLayer = this._currentFeature?.layer;
    const allTables = this.mapView && await getAllTables(this.mapView);
    selectedLayer.relationships?.some((relationship) => {
      const relatedTables = allTables?.filter((table) => selectedLayer.url === table.url && table.layerId === relationship.relatedTableId);
      if (relatedTables && relatedTables.length > 0) {
        this._relatedTable = relatedTables[0];
        return true;
      } else {
        return false;
      }
    });
  }
  async updatingFeatureDetails(isLoading) {
    this._showLoadingIndicator = isLoading;
  }
  async selectionChanged(_evt) {
    void this.updatingFeatureDetails(true);
    await this.setCurrentFeature(_evt.detail.selectedFeature[0]);
    void this.highlightOnMap(_evt.detail.selectedFeature[0]);
    this._selectedFeatureIndex = _evt.detail.selectedFeatureIndex;
    this._featureDetails.value && await this._featureDetails.value.refresh(_evt.detail.selectedFeature[0]);
  }
  showAddCommentsPanel() {
    this._flowItems = [...this._flowItems, "add-comment"];
  }
  async onCommentSelectFromList(_evt) {
    this._selectedRelatedFeature = [_evt.detail];
    this._flowItems = [...this._flowItems, "comment-details"];
  }
  getFeatureListFlowItem(layerId, layerName) {
    const canCreateReports = this._getLayersConfig(this._selectedLayerId)?.reporting && this._layerItemsHash && this._layerItemsHash[this._selectedLayerId].supportsAdd;
    const showFilterIcon = this._currentLayerExpressions?.length;
    return html`<calcite-flow-item .collapsed=${this.isMobile && this._sidePanelCollapsed} .heading=${layerName} .loading=${!this.isMobile && this._showLoadingIndicator} @calciteFlowItemBack=${this.backFromSelectedPanel} .selected=${this._flowItems[this._flowItems.length - 1] === "feature-list"}>${this._toggleSort()}<calcite-action appearance=solid icon=sort-ascending-arrow id=sort-popover slot=header-actions-end .text=${this._translations.sort} title=${this._translations.sort ?? nothing}></calcite-action>${showFilterIcon && html`<calcite-action appearance=solid icon=filter .indicator=${this._filterActive} @click=${() => {
      this.isMobile ? this._toggleFilter() : this._flowItems = [...this._flowItems, "filter-panel"];
    }} slot=header-actions-end .text=${this._translations.filter} title=${this._translations.filter ?? nothing}></calcite-action>` || ""}${this.isMobile && this.getActionToExpandCollapsePanel() || ""}${this.enableNewReports && canCreateReports && html`<calcite-button appearance=solid @click=${this.navigateToCreateFeature} slot=footer width=full>${this.reportButtonText ? this.reportButtonText : this._translations.createReportButtonText}</calcite-button>` || ""}<calcite-panel>${html`<feature-list .applyLayerViewFilter=${this.showMyReportsOnly} class="height-full" .filterByMapExtent=${this.filterByMapExtent} highlight-on-hover .mapView=${this.mapView} .noFeaturesFoundMsg=${this._translations.featureErrorMsg} @featureClick=${() => {
      this._showLoadingIndicator = true;
    }} @featureSelect=${this.onFeatureSelectFromList} page-size=30 .reportingOptions=${this.reportingOptions} .selectedLayerId=${layerId} .showFeatureSymbol=${this.showFeatureSymbol} .sortingInfo=${this._updatedSorting} ${ref(this._featureList)}></feature-list>`}</calcite-panel></calcite-flow-item>`;
  }
  getFilterPanel() {
    return html`<calcite-flow-item .collapsed=${this.isMobile && this._sidePanelCollapsed} .heading=${this._translations.filterLayerTitle.replace("{{title}}", this._selectedLayerName)} .loading=${this._showLoadingIndicator} @calciteFlowItemBack=${this.backFromFilterPanel} .selected=${this._flowItems[this._flowItems.length - 1] === "filter-panel"}>${this.isMobile && this.getActionToExpandCollapsePanel() || ""}<div class=width-full slot=footer><div class=width-full slot=footer><calcite-button appearance=solid class="footer-top-button footer-button" .disabled=${!this._filterActive} @click=${this.resetFilterList} width=full>${this._translations.resetFilter}</calcite-button><calcite-button appearance=outline class=footer-button @click=${this.backFromFilterPanel} width=full>${this._translations.close}</calcite-button></div></div><calcite-panel>${this.mapView && html`<instant-apps-filter-list .closeBtnOnClick=${() => void 0} combobox-overlay-positioning=fixed .layerExpressions=${this._currentLayerExpressions} @filterListReset=${() => void this._handleFilterListReset()} @filterUpdate=${() => {
      const filterCount = this._filterList?.filterCount;
      if (filterCount !== void 0) {
        void this._handleFilterUpdate(filterCount > 0);
      }
    }} .view=${this.mapView} ${ref(this._setFilterList)}></instant-apps-filter-list>` || ""}</calcite-panel></calcite-flow-item>`;
  }
  getFeatureDetailsFlowItem() {
    const relationships = this._selectedLayer?.relationships;
    const showCommentBtn = this._getLayersConfig(this._selectedLayerId)?.comment && relationships && relationships.length > 0 && this._relatedTable;
    return html`<calcite-flow-item .collapsed=${this.isMobile && this._sidePanelCollapsed} .heading=${this._selectedLayerName} .loading=${this._showLoadingIndicator} @calciteFlowItemBack=${this.backFromSelectedPanel} .selected=${this._flowItems[this._flowItems.length - 1] === "feature-details"}>${this.isMobile && this.getActionToExpandCollapsePanel() || ""}${this.mapView && html`<instant-apps-social-share class=share-node flip-rtl popover-button-icon-scale=s remove-popover-offset scale=m share-button-color=neutral share-button-type=action slot=header-actions-end social-media .view=${this.mapView} ${ref(this._shareNode)}></instant-apps-social-share>` || ""}${this._selectedFeature.length > 1 && this.getFeaturesPagination() || ""}<calcite-panel><feature-details class=full-height .enableSnapping=${this.enableSnapping} .graphics=${this._selectedFeature} .layerItemsHash=${this._layerItemsHash} .mapView=${this.mapView} @addComment=${this.showAddCommentsPanel} @commentClick=${() => {
      this._showLoadingIndicator = true;
    }} @commentSelect=${this.onCommentSelectFromList} @featureSelectionChange=${this.selectionChanged} @likeOrDislikeClicked=${() => {
      this._featureList.value && void this._featureList.value.refresh(true);
    }} @loadingStatus=${(_evt) => void this.updatingFeatureDetails(_evt.detail)} .reportingOptions=${this.reportingOptions} .showFullCommentTitle=${this.showFullCommentTitle} .showUserImageInCommentsList=${this.showUserImageInCommentsList} ${ref(this._featureDetails)}></feature-details>${showCommentBtn && html`<calcite-button appearance=solid @click=${this.showAddCommentsPanel} slot=footer width=full>${this.commentButtonText || this._translations.comment}</calcite-button>` || ""}</calcite-panel></calcite-flow-item>`;
  }
  getFeaturesPagination() {
    return html`<div class="feature-pagination"><div><calcite-button appearance=transparent icon-start=chevron-left icon-flip-rtl=both id=solutions-back @click=${() => this._featureDetails.value && void this._featureDetails.value.back()} scale=s width=full></calcite-button><calcite-tooltip placement=top reference-element=solutions-back><span>${this._translations.back}</span></calcite-tooltip></div><calcite-button appearance=transparent @click=${() => this._featureDetails.value && void this._featureDetails.value.toggleListView()} scale=s><span class="pagination-count">${this._getCount()}</span></calcite-button><div><calcite-button appearance=transparent icon-flip-rtl=both icon-start=chevron-right id=solutions-next @click=${() => this._featureDetails.value && void this._featureDetails.value.next()} scale=s width=full></calcite-button><calcite-tooltip placement=top reference-element=solutions-next><span>${this._translations.next}</span></calcite-tooltip></div></div>`;
  }
  getCommentDetailsFlowItem() {
    return html`<calcite-flow-item .collapsed=${this.isMobile && this._sidePanelCollapsed} .heading=${this._relatedTable?.title || ""} @calciteFlowItemBack=${this.backFromSelectedPanel} .selected=${this._flowItems[this._flowItems.length - 1] === "comment-details"}>${this.isMobile && this.getActionToExpandCollapsePanel() || ""}<calcite-panel><info-card .enableSnapping=${this.enableSnapping} .graphics=${this._selectedRelatedFeature} .mapView=${this.mapView} @selectionChanged=${() => {
      this._showLoadingIndicator = false;
    }}></info-card></calcite-panel></calcite-flow-item>`;
  }
  getAddCommentFlowItem() {
    return html`<calcite-flow-item .collapsed=${this.isMobile && this._sidePanelCollapsed} .heading=${this._relatedTable?.title || ""} @calciteFlowItemBack=${this.backFromCreateRelatedFeaturePanel} .selected=${this._flowItems[this._flowItems.length - 1] === "add-comment"}>${this.isMobile && this.getActionToExpandCollapsePanel() || ""}<div class=width-full slot=footer>${this._showSubmitCancelButton && html`<div class=width-full slot=footer><calcite-button appearance=solid class="footer-top-button footer-button" @click=${this.onCreateRelatedFeatureSubmitButtonClick} width=full>${this._translations.submit}</calcite-button><calcite-button appearance=outline class=footer-button @click=${this.backFromCreateRelatedFeaturePanel} width=full>${this._translations.cancel}</calcite-button></div>` || ""}</div><calcite-panel><create-related-feature customize-submit .enableSnapping=${this.enableSnapping} .mapView=${this.mapView} @fail=${this.addCommentFailed} @formReady=${this.onFormReady} @isActionPending=${this.showSubmitCancelButton} @success=${this.onCommentSubmitted} .selectedFeature=${this._currentFeature} .table=${this._relatedTable} ${ref(this._createRelatedFeature)}></create-related-feature></calcite-panel></calcite-flow-item>`;
  }
  async setSelectedFeatures(features) {
    this._selectedFeature = features;
    await this.setCurrentFeature(this._selectedFeature.length ? this._selectedFeature[0] : void 0);
  }
  async setCurrentFeature(selectedFeature) {
    this._currentFeature = selectedFeature;
    if (selectedFeature && selectedFeature.layer) {
      const layer = selectedFeature.layer;
      layer.title && void this.setSelectedLayer(layer.id, layer.title);
      this._currentFeatureId = selectedFeature.attributes[layer.objectIdField];
      const isCommentTablePresent = this._getLayersConfig(layer.id)?.comment && layer.relationships && layer.relationships.length > 0;
      if (isCommentTablePresent) {
        await this.getRelatedTable();
      }
    } else {
      if (this._editableLayerIds.length > 1) {
        void this.setSelectedLayer("", "");
        void this.handlePrevLayersFilter();
      }
      this._currentFeatureId = "";
    }
    this._updateShareURL();
  }
  async highlightOnMap(selectedFeature) {
    this.clearHighlights();
    if (selectedFeature && selectedFeature.geometry && selectedFeature.layer && selectedFeature.layer.id !== void 0) {
      const selectedLayerView = this.mapView && await getFeatureLayerView(this.mapView, selectedFeature.layer.id.toString());
      if (selectedLayerView) {
        const oid = Number(selectedFeature.getObjectId());
        this._highlightHandle = this.mapView && await highlightFeatures([oid], selectedLayerView, this.mapView, true, this.zoomToScale);
      }
    }
    void this.updatingFeatureDetails(false);
  }
  clearHighlights() {
    if (this._highlightHandle) {
      this._highlightHandle.remove();
    }
  }
  getActionToExpandCollapsePanel() {
    return html`<calcite-action appearance=solid .icon=${this._sidePanelCollapsed ? "chevrons-up" : "chevrons-down"} @click=${this.toggleSidePanel} slot=header-actions-end .text=${(this._sidePanelCollapsed ? this._translations.expand : this._translations.collapse) || ""}></calcite-action>`;
  }
  async setMapView() {
    this.mapView && await getAllTables(this.mapView);
    await this.getLayersToShowInList();
    await this._updateFeatures();
    if (this._editableLayerIds?.length === 1) {
      await this.renderFeaturesList();
    } else {
      this._flowItems = ["layer-list"];
    }
    if (this.mapView) {
      this.mapView.popupEnabled = false;
      if (this._defaultCenter && this._defaultLevel) {
        await this.mapView.goTo({
          center: this._defaultCenter,
          zoom: this._defaultLevel
        });
        this._defaultCenter = void 0;
        this._defaultLevel = void 0;
      }
    }
  }
  handleMapClick() {
    if (this._mapClickHandle) {
      this._mapClickHandle.remove();
    }
    this._mapClickHandle = reactiveUtils.on(() => this.mapView, "click", (event) => {
      if (this.mapView) {
        this.mapView.popupEnabled = false;
      }
      void this.onMapClick(event);
    });
  }
  async onMapClick(event) {
    if (this._flowItems[this._flowItems.length - 1] === "feature-create" || this._flowItems[this._flowItems.length - 1] === "add-comment") {
      return;
    }
    if (this.mapView) {
      const hitTest = await this.mapView.hitTest(event);
      const clickedGraphics = [];
      let nonReportingLayerGraphics = [];
      let identifyGraphics = [];
      let hasIdentifiedGraphics = false;
      if (hitTest.results.length > 0) {
        hitTest.results.forEach((result) => {
          if (result.type === "graphic") {
            clickedGraphics.push(result.graphic);
          }
        });
      }
      if (clickedGraphics.length > 0) {
        await this._setReportingGraphics(clickedGraphics);
        nonReportingLayerGraphics = this._getNonReportingLayerGraphics(clickedGraphics);
      }
      if (this._mapImageryLayersId.length > 0) {
        identifyGraphics = await this._getIdentifiedGraphics(event.mapPoint);
        hasIdentifiedGraphics = identifyGraphics.length > 0;
      }
      const graphics = nonReportingLayerGraphics.concat(identifyGraphics);
      if (graphics.length > 0) {
        this.mapView.popupEnabled = true;
        const options = {
          features: graphics,
          location: event.mapPoint,
          updateLocationEnabled: !hasIdentifiedGraphics
          // if identify graphics is present then dont update location
        };
        await this.mapView.openPopup(options);
      }
    }
  }
  async _setReportingGraphics(clickedGraphics) {
    const reportingLayerGraphics = clickedGraphics.filter((graphic) => {
      if (graphic.layer?.type === "feature") {
        const layer = graphic.layer;
        return this._validLayers.includes(layer);
      } else {
        return false;
      }
    });
    if (this._selectedLayer && this._selectedFeature.length > 0 && this._selectedLayer.id === reportingLayerGraphics[0]?.layer?.id && reportingLayerGraphics[0].attributes[this._selectedLayer.objectIdField] === this._selectedFeature[0].attributes[this._selectedLayer.objectIdField]) {
      return;
    }
    if (reportingLayerGraphics.length > 0) {
      await this.setSelectedFeatures(reportingLayerGraphics);
      if (this._flowItems.length && this._flowItems.includes("feature-details")) {
        this._flowItems = [...this._flowItems.slice(0, this._flowItems.indexOf("feature-details") + 1)];
        await this.highlightOnMap(clickedGraphics[0]);
      } else {
        this._flowItems = [...this._flowItems, "feature-details"];
      }
    }
  }
  _getNonReportingLayerGraphics(clickedGraphics) {
    const nonReportingLayerGraphics = clickedGraphics.filter((graphic) => {
      if (graphic.layer?.type === "feature") {
        const layer = graphic.layer;
        return !this._validLayers.includes(layer) && layer?.popupEnabled && layer?.id;
      } else {
        return false;
      }
    });
    return nonReportingLayerGraphics;
  }
  async _getIdentifiedGraphics(mapPoint) {
    const params = new IdentifyParameters({
      geometry: mapPoint,
      tolerance: 3,
      mapExtent: this.mapView?.extent
    });
    let identifiedLayer;
    let identifyResults = [];
    for (const layerId of this._mapImageryLayersId) {
      const layer = this.mapView && await getLayerOrTable(this.mapView, layerId);
      if (layer?.url && params) {
        try {
          const result = await identify?.identify(layer.url, params);
          if (result?.results?.length) {
            identifyResults = result.results;
            identifiedLayer = layer;
            break;
          }
        } catch (error) {
          console.error(error);
        }
      }
    }
    const graphics = [];
    identifyResults.forEach((result) => {
      const layerId = result.layerId;
      const subLayer = identifiedLayer?.sublayers?.items.find((l) => l.id === layerId);
      const popupTemplate = subLayer?.popupTemplate;
      if (subLayer?.popupEnabled && popupTemplate) {
        result.feature.popupTemplate = popupTemplate;
        graphics.push(result.feature);
      }
    });
    return graphics;
  }
  _getCount() {
    const index = (this._selectedFeatureIndex + 1).toString();
    const total = this._selectedFeature.length.toString();
    return this._translations.indexOfTotal.replace("{{index}}", index).replace("{{total}}", total);
  }
  _updateFloorDefinitionExpression(layer) {
    const floorField = layer?.floorInfo?.floorField;
    const floorExp = `${floorField} = '${this.floorLevel}'`;
    const defExp = layer.definitionExpression;
    layer.definitionExpression = defExp && defExp?.indexOf(this._floorExpression) > -1 ? defExp.replace(this._floorExpression, floorExp) : floorExp;
    this._floorExpression = floorExp;
  }
  _getFormElements() {
    const layer = this._selectedLayer;
    const floorField = layer?.floorInfo?.floorField;
    if (floorField && this.floorLevel && layer?.formTemplate) {
      const formElement = this._formElements.find((elm) => elm.id === layer.id);
      if (this._formElements.length === 0 || !formElement) {
        this._formElements.push({
          id: layer.id,
          orgElements: layer.formTemplate.elements,
          orgExpressionInfos: layer.formTemplate.expressionInfos
        });
      }
    }
  }
  reduceToConfiguredLayers(hash, layersEditingDisabled) {
    return Object.keys(hash).reduce((prev, cur) => {
      const showLayer = this.reportingOptions ? this._getLayersConfig(cur)?.visible : hash[cur].supportsAdd;
      if (!layersEditingDisabled.includes(cur) && showLayer) {
        prev.push(cur);
      }
      return prev;
    }, []);
  }
  refreshLists() {
    setTimeout(() => {
      if (this._layerList.value && this._flowItems[this._flowItems.length - 1] === "layer-list") {
        void this._layerList.value.refresh();
      }
      if (this._featureList.value) {
        void this._featureList.value.refresh();
      }
    }, 50);
  }
  async _updateFeatures() {
    for (const eachLayerId of this._editableLayerIds) {
      const featureLayerView = this.mapView && await getFeatureLayerView(this.mapView, eachLayerId);
      if (featureLayerView) {
        await this._showMyFeaturesOnly(featureLayerView);
        const floorField = featureLayerView.layer?.floorInfo?.floorField;
        if (floorField && this.floorLevel) {
          this._updateFloorDefinitionExpression(featureLayerView.layer);
        }
      }
    }
  }
  async _showMyFeaturesOnly(featureLayerView) {
    const loggedInUserName = (this.mapView?.map).portalItem.portal?.credential?.userId;
    if (loggedInUserName && featureLayerView) {
      const creatorField = featureLayerView.layer.editFieldsInfo?.creatorField.toLowerCase();
      featureLayerView.filter = this.showMyReportsOnly && creatorField ? new FeatureFilter({
        where: `${creatorField} = '${loggedInUserName}'`
      }) : null;
    }
  }
  async getLayersToShowInList() {
    const layerItemsHash = this.mapView && await getMapLayerHash(this.mapView, true);
    const allMapLayers = this.mapView && await getAllFeatureLayers(this.mapView);
    const layersEditingDisabled = [];
    allMapLayers?.forEach((eachLayer) => {
      if (eachLayer?.type === "feature" && eachLayer?.editingEnabled && eachLayer?.capabilities?.operations?.supportsAdd) {
        layerItemsHash[eachLayer.id].supportsAdd = true;
      }
      if (!eachLayer?.editingEnabled) {
        layersEditingDisabled.push(eachLayer.id);
      }
    });
    this._editableLayerIds = this.reduceToConfiguredLayers(layerItemsHash, layersEditingDisabled);
    this._layerItemsHash = layerItemsHash;
  }
  async renderFeaturesList() {
    this._flowItems = ["feature-list"];
    const _evt = {
      detail: this._editableLayerIds
    };
    await this.layerListLoaded(_evt);
    await this.setSelectedLayer(this._validLayers[0].id, this._validLayers[0]?.title || "");
    this.updateSortingOptions();
    await this.handleSelectedLayersFilter();
    if (!this._urlParamsLoaded) {
      this._urlParamsLoaded = true;
      await this.loadFeatureFromURLParams();
    }
  }
  _updateShareURL() {
    const url = this._shareNode.value?.shareUrl;
    if (!url) {
      return;
    }
    const urlObj = new URL(url);
    if (this._selectedLayerId) {
      urlObj.searchParams.set("layerid", this._selectedLayerId);
    } else {
      urlObj.searchParams.delete("layerid");
    }
    if (this._selectedFeature?.length) {
      urlObj.searchParams.set("oid", this._currentFeatureId);
    } else {
      urlObj.searchParams.delete("oid");
    }
    if (this._shareNode.value) {
      this._shareNode.value.autoUpdateShareUrl = false;
      this._shareNode.value.shareUrl = urlObj.href;
    }
  }
  async loadFeatureFromURLParams() {
    if (this.center && this.level) {
      await this.mapView?.goTo({
        center: this.center.split(";").map(Number),
        zoom: parseInt(this.level, 10)
      });
    }
    if (this.layerId && this.objectId) {
      const layer = this.mapView && await getLayerOrTable(this.mapView, this.layerId);
      if (layer) {
        const featureSet = this.mapView && await queryFeaturesByID([Number(this.objectId)], layer, [], true, this.mapView.spatialReference);
        if (featureSet?.length) {
          await this.setSelectedFeatures(featureSet);
          if (this._flowItems.length && this._flowItems[this._flowItems.length - 1] !== "feature-details") {
            this._flowItems = [...this._flowItems, "feature-details"];
          } else {
            this._flowItems = [...this._flowItems];
          }
        }
      }
    }
  }
  async handleSelectedLayersFilter() {
    if (this._selectedLayer) {
      const currentLayerExpressions = this.layerExpressions ? structuredClone(this.layerExpressions.filter((exp) => exp.id === this._selectedLayerId)) : [];
      if (this._t9nLayerExpressions != null) {
        this.handleLayerExpressionsT9n(currentLayerExpressions, this._t9nLayerExpressions);
      }
      this._currentLayerExpressions = currentLayerExpressions;
      this.setActiveDefinitionExpressions();
    }
  }
  async handlePrevLayersFilter() {
    if (this._prevSelectedLayerId) {
      const prevLayer = this.mapView && await getLayerOrTable(this.mapView, this._prevSelectedLayerId);
      if (prevLayer && this._initDefExpressions) {
        prevLayer.definitionExpression = this._initDefExpressions[this._prevSelectedLayerId];
      }
    }
  }
  async resetFilterList() {
    await this._filterList?.forceReset();
    if (this._selectedLayer !== void 0 && this._initDefExpressions) {
      this._selectedLayer.definitionExpression = this._initDefExpressions[this._selectedLayerId];
      this._filterActive = false;
    }
  }
  setActiveDefinitionExpressions() {
    if (this._selectedLayer === void 0) {
      return;
    }
    const defExpressions = [];
    if (this._currentLayerExpressions && this._currentLayerExpressions?.length > 0) {
      const layerExpression = this._currentLayerExpressions[0];
      for (const expression of layerExpression.expressions) {
        const { active, definitionExpression } = expression;
        if (active && definitionExpression) {
          defExpressions.push(`(${definitionExpression})`);
        }
      }
      this._filterActive = defExpressions.length > 0;
      this.updateFilterLayerDefExpression(defExpressions, layerExpression.operator);
    }
  }
  updateFilterLayerDefExpression(defExpressions, operator) {
    const initDefExpression = this._initDefExpressions && this._initDefExpressions[this._selectedLayerId];
    const combinedExpressions = defExpressions?.length > 0 && initDefExpression ? `(${defExpressions.join(operator)}) AND (${initDefExpression})` : defExpressions.length > 0 ? defExpressions.join(operator) : initDefExpression;
    if (this._selectedLayer) {
      this._selectedLayer.definitionExpression = combinedExpressions;
    }
  }
  setInitExpressions() {
    this._initDefExpressions = {};
    if (this.mapView == null) {
      return;
    }
    const map = this.mapView.map;
    map.allLayers.concat(map.allTables.toArray()).forEach((layer) => {
      if (layer.type === "map-image" && layer.popupEnabled && !this._mapImageryLayersId.includes(layer.id)) {
        this._mapImageryLayersId.push(layer.id);
        return;
      }
      if (layer.type !== "feature") {
        return;
      }
      const fl = layer;
      if (this._initDefExpressions) {
        this._initDefExpressions[fl.id] = fl.definitionExpression || "";
      }
    });
  }
  handleLayerExpressionsT9n(layerExpressions, layerExpressionsT9n) {
    layerExpressions?.forEach((layerExpression) => {
      const t9nLayerExpression = layerExpressionsT9n?.find((t9nLayerExpression2) => t9nLayerExpression2.id === layerExpression.id);
      if (t9nLayerExpression != null) {
        layerExpression.title = t9nLayerExpression.title;
        layerExpression.expressions?.forEach((expression) => {
          const t9nExpression = t9nLayerExpression.expressions?.find((t9nExpression2) => t9nExpression2.id === expression.id);
          if (t9nExpression != null) {
            expression.name = t9nExpression.name;
          }
        });
      }
    });
  }
}
customElement("crowdsource-reporter", CrowdsourceReporter);
export {
  CrowdsourceReporter
};
