/* COPYRIGHT Esri - https://js.arcgis.com/1.2/LICENSE.txt */
import { g as getAssetPath, c as customElement } from "../../chunks/runtime.js";
import { e as goToSelection, h as highlightFeatures } from "../../chunks/mapViewUtils.js";
import { c as consolidateLabels, r as removeDuplicateLabels } from "../../chunks/downloadUtils.js";
import { u as useT9n } from "../../chunks/useT9n.js";
import { css, nothing, html } from "lit";
import { createRef, ref } from "lit-html/directives/ref.js";
import { LitElement, createEvent, noShadowRoot, safeClassMap } from "@arcgis/lumina";
import { p as pnContext } from "../../chunks/publicNotificationContext.js";
import { useContextProvider } from "@arcgis/lumina/context";
import "../refine-selection/customElement.js";
import Graphic from "@arcgis/core/Graphic";
import { Controller } from "@arcgis/lumina/controllers";
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-input-message-spacing-value: 0;
}

.align-center {
  align-items: center;
}

.border-bottom-1 {
  border-width: 0px;
  border-bottom-width: 1px;
  border-style: solid;
  border-color: var(--calcite-color-border-3);
}

.action-bar-size {
  height: 3.5rem;
  width: 100%;
}

.w-1-2 {
  width: 50%;
}

.w-1-3 {
  width: 33.33%;
}

.width-full {
  width: 100%;
}

.height-full {
  height: 100%;
}

.padding-1 {
  padding: 1rem;
}

.padding-top-sides-1 {
  padding-block-start: 1rem;
  padding-inline-start: 1rem;
  padding-inline-end: 1rem;
}

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

.padding-top-1-2 {
  padding-block-start: 0.5rem;
}

.padding-top-1 {
  padding-top: 1rem;
}

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

.info-blue {
  /* This would be better but not the right color in light theme */
  /* color: var(--calcite-color-info); */

  /* This is --calcite-color-info value for dark theme*/
  color: #00a0ff;
}

.info-message {
  justify-content: center;
  display: grid;
}

.font-bold {
  font-weight: bold;
}

.display-flex {
  display: flex;
}

.display-block {
  display: block;
}

.display-none {
  display: none;
}

.border-bottom {
  border-bottom: 1px solid var(--calcite-color-border-2);
}

.padding-start-1-2 {
  padding-inline-start: 0.5rem;
}

.list-border {
  border: 1px solid var(--calcite-color-border-2);
}

.margin-sides-1 {
  margin-inline-start: 1rem;
  margin-inline-end: 1rem;
}

.margin-start-1-2 {
  margin-inline-start: 0.5rem;
}

.margin-top-0 {
  margin-block-start: 0 !important;
}

.label-margin-0 {
  --calcite-label-margin-bottom: 0;
}

.list-label {
  color: var(--calcite-color-text-1);
}

.list-label,
.list-description {
  font-family: var(--calcite-sans-family);
  font-size: var(--calcite-font-size--2);
  font-weight: var(--calcite-font-weight-normal);
  overflow-wrap: break-word;
  word-break: break-word;
}

.list-description {
  margin-block-start: 0.125rem;
  color: var(--calcite-color-text-3);
}

.img-container {
  width: 100%;
  height: 100%;
}

.font-weight-500 {
  font-weight: 500;
}

.background-override {
  height: 100%;
  width: 100%;
  --calcite-color-foreground-3: var(--calcite-color-brand);
  --calcite-color-foreground-2: var(--calcite-color-brand-hover);
  --calcite-color-text-1: var(--calcite-color-text-inverse);
}

.word-wrap-anywhere {
  word-wrap: anywhere;
}

.tooltip-message {
  padding: 5px 8px;
  font-weight: var(--calcite-font-weight-normal);
  color: var(--calcite-color-text-2);
  max-width: 400px;
}

calcite-action-bar {
  --calcite-internal-action-bar-gap: 0px;
  --calcite-internal-action-bar-padding: 0px;
}
}`;
class PNStateController extends Controller {
  constructor() {
    super();
    this.managedLayers = {};
    this.managedTables = [];
    this.highlightHandles = [];
  }
  // remove all handles
  removeHandles() {
    this.highlightHandles.forEach((h) => {
      h?.remove();
    });
    this.highlightHandles = [];
  }
}
class PublicNotification extends LitElement {
  constructor() {
    super();
    this.addresseeLayerIds = [];
    this.bufferColor = [227, 139, 79, 0.8];
    this.bufferOutlineColor = [255, 255, 255];
    this.customLabelEnabled = false;
    this.defaultBufferDistance = 0;
    this.defaultBufferUnit = "feet";
    this.defaultExportTitle = "";
    this.defaultNumLabelsPerPage = 6;
    this.enableLayerFeatures = true;
    this.enableLayerFeaturesOnLoad = false;
    this.enableSearchDistance = true;
    this.enableSearchDistanceOnLoad = false;
    this.enableSketchTools = true;
    this.featureHighlightEnabled = false;
    this.noResultText = "";
    this.initialNotice = "";
    this.selectionLayerIds = [];
    this.showRefineSelection = false;
    this.showSearchSettings = true;
    this._exportGraphics = false;
    this._addMap = false;
    this._addResults = true;
    this._addTitle = false;
    this._downloadActive = true;
    this._exportType = "PDF";
    this._fetchingData = false;
    this._isMobile = false;
    this._numDuplicates = 0;
    this._pageType = "LIST";
    this._saveEnabled = false;
    this._selectionSets = [];
    this._translations = useT9n({ name: "public-notification", blocking: true });
    this._downloadTools = createRef();
    this._onboardingImageUrl = "";
    this._popupsEnabled = false;
    this._removeDuplicates = createRef();
    this._selectTools = createRef();
    this._refineSelection = createRef();
    this._titleElement = createRef();
    this._titleValue = void 0;
    this._numSelected = 0;
    this._pnStateContextProvider = useContextProvider({ context: pnContext });
    this._refineGraphics = [];
    this.searchConfigurationChange = createEvent();
    this.listenOn(window, "selectionSetsChanged", this.selectionSetsChanged);
    this._pnState = new PNStateController();
    this._pnStateContextProvider.setValue(this._pnState);
  }
  static {
    this.properties = { addresseeLayerIds: [0, {}, { attribute: false }], bufferColor: 1, bufferOutlineColor: 1, customLabelEnabled: [5, {}, { type: Boolean }], defaultBufferDistance: [9, {}, { type: Number }], defaultBufferUnit: 1, defaultExportTitle: 1, defaultNumLabelsPerPage: [9, {}, { type: Number }], enableLayerFeatures: [5, {}, { type: Boolean }], enableLayerFeaturesOnLoad: [5, {}, { type: Boolean }], enableSearchDistance: [5, {}, { type: Boolean }], enableSearchDistanceOnLoad: [5, {}, { type: Boolean }], enableSketchTools: [5, {}, { type: Boolean }], featureEffect: [0, {}, { attribute: false }], featureHighlightEnabled: [5, {}, { type: Boolean }], mapView: [0, {}, { attribute: false }], noResultText: 1, initialNotice: 1, searchConfiguration: [0, {}, { attribute: false }], selectionLayerIds: [0, {}, { attribute: false }], showRefineSelection: [5, {}, { type: Boolean }], showSearchSettings: [5, {}, { type: Boolean }], sketchLineSymbol: [0, {}, { attribute: false }], sketchPointSymbol: [0, {}, { attribute: false }], sketchPolygonSymbol: [0, {}, { attribute: false }], _exportGraphics: [16, {}, { state: true }], _addMap: [16, {}, { state: true }], _addResults: [16, {}, { state: true }], _addTitle: [16, {}, { state: true }], _downloadActive: [16, {}, { state: true }], _exportType: [16, {}, { state: true }], _fetchingData: [16, {}, { state: true }], _isMobile: [16, {}, { state: true }], _numDuplicates: [16, {}, { state: true }], _pageType: [16, {}, { state: true }], _saveEnabled: [16, {}, { state: true }], _selectionSets: [16, {}, { state: true }], _translations: [16, {}, { state: true }] };
  }
  static {
    this.styles = styles;
  }
  static {
    this.shadowRootOptions = noShadowRoot;
  }
  willUpdate(changes) {
    if (changes.has("mapView") && this.mapView) {
      void this.mapViewWatchHandler(this.mapView);
    }
    if (changes.has("searchConfiguration") && this.searchConfiguration) {
      void this.watchSearchConfigurationHandler(this.searchConfiguration, changes.get("searchConfiguration"));
    }
    if (changes.has("sketchLineSymbol")) {
      void this.sketchLineSymbolWatchHandler(this.sketchLineSymbol, changes.get("sketchLineSymbol"));
    }
    if (changes.has("sketchPointSymbol")) {
      void this.sketchPointSymbolWatchHandler(this.sketchPointSymbol, changes.get("sketchPointSymbol"));
    }
    if (changes.has("sketchPolygonSymbol")) {
      void this.sketchPolygonSymbolWatchHandler(this.sketchPolygonSymbol, changes.get("sketchPolygonSymbol"));
    }
    if (changes.has("_pageType") && (this.hasUpdated || this._pageType !== "LIST")) {
      void this.pageTypeWatchHandler(this._pageType, changes.get("_pageType"));
    }
  }
  async mapViewWatchHandler(v) {
    if (v?.popup) {
      this._popupsEnabled = v?.popupEnabled;
    }
    this.searchConfiguration && this._initSearchConfiguration(this.searchConfiguration);
  }
  async watchSearchConfigurationHandler(newValue, oldValue) {
    const s_newValue = JSON.stringify(newValue);
    if (this.mapView && (s_newValue !== JSON.stringify(oldValue) || s_newValue && !this._searchConfiguration)) {
      this._searchConfiguration = JSON.parse(s_newValue);
      this._searchConfiguration && this.searchConfigurationChange.emit(this._searchConfiguration);
      void this._home();
    }
  }
  async sketchLineSymbolWatchHandler(v, oldV) {
    if (v && JSON.stringify(v) !== JSON.stringify(oldV)) {
      this._setLineSymbol(v);
    }
  }
  async sketchPointSymbolWatchHandler(v, oldV) {
    if (v && JSON.stringify(v) !== JSON.stringify(oldV)) {
      this._setPointSymbol(v);
    }
  }
  async sketchPolygonSymbolWatchHandler(v, oldV) {
    if (v && JSON.stringify(v) !== JSON.stringify(oldV)) {
      this._setPolygonSymbol(v);
    }
  }
  async pageTypeWatchHandler(pageType, oldPageType) {
    this._checkPopups();
    if (this.mapView?.popup) {
      this.mapView.popupEnabled = pageType !== "LIST" ? false : this._popupsEnabled;
    }
    if (pageType === "EXPORT") {
      this._fetchingData = true;
      this._numDuplicates = await this._getNumDuplicates();
      this._updateExportGraphics();
      this._fetchingData = false;
    }
    this._clearHighlight();
    if (oldPageType === "SELECT" || oldPageType === "REFINE") {
      await this._clearSelection();
    }
    if (oldPageType === "EXPORT") {
      this._removeExportGraphics();
    }
    if (pageType !== "SELECT") {
      return this._highlightFeatures();
    }
  }
  selectionSetsChanged(event) {
    this._selectionSets = [...event.detail];
  }
  connectedCallback() {
    super.connectedCallback();
    this._mediaQuery = window.matchMedia("(max-width: 600px)");
    this.listenOn(this._mediaQuery, "change", (_evt) => this._setIsMobile(_evt));
  }
  async load() {
    this._initSymbols();
    this._onboardingImageUrl = getAssetPath(`assets/public-notification/images/onboarding.png`);
  }
  render() {
    const headerSlot = this._isMobile ? "footer" : "header";
    return html`<calcite-shell><calcite-action-bar class="border-bottom-1 action-bar-size" expand-disabled layout=horizontal slot=${headerSlot ?? nothing}>${this._getActionGroup("list-check", "LIST", this._translations.myLists)}${this.showRefineSelection ? this._getActionGroup("test-data", "REFINE", this._translations.refineSelection) : null}${this._getActionGroup("export", "EXPORT", this._translations.export)}</calcite-action-bar>${this._getPage(this._pageType)}</calcite-shell>`;
  }
  loaded() {
    this.searchConfiguration && this._initSearchConfiguration(this.searchConfiguration);
  }
  _initSearchConfiguration(v) {
    if (this.searchConfiguration && !this._searchConfiguration && this.mapView) {
      this._searchConfiguration = v;
      this.searchConfigurationChange.emit(this._searchConfiguration);
      void this._home();
    }
  }
  _initSymbols() {
    this._setLineSymbol(this.sketchLineSymbol);
    this._setPointSymbol(this.sketchPointSymbol);
    this._setPolygonSymbol(this.sketchPolygonSymbol);
  }
  _setLineSymbol(v) {
    const isSymbol = v?.type === "simple-line";
    this.sketchLineSymbol = isSymbol ? v : this._jsonUtils?.fromJSON(v ? v : {
      type: "esriSLS",
      color: [130, 130, 130, 255],
      width: 2,
      style: "esriSLSSolid"
    });
  }
  _setPointSymbol(v) {
    const isSymbol = v?.type === "simple-marker";
    this.sketchPointSymbol = isSymbol ? v : this._jsonUtils?.fromJSON(v ? v : {
      type: "esriSMS",
      color: [255, 255, 255, 255],
      angle: 0,
      xoffset: 0,
      yoffset: 0,
      size: 6,
      style: "esriSMSCircle",
      outline: {
        type: "esriSLS",
        color: [50, 50, 50, 255],
        width: 1,
        style: "esriSLSSolid"
      }
    });
  }
  _setPolygonSymbol(v) {
    const isSymbol = v?.type === "simple-fill";
    this.sketchPolygonSymbol = isSymbol ? v : this._jsonUtils?.fromJSON(v ? v : {
      type: "esriSFS",
      color: [150, 150, 150, 51],
      outline: {
        type: "esriSLS",
        color: [50, 50, 50, 255],
        width: 2,
        style: "esriSLSSolid"
      },
      style: "esriSFSSolid"
    });
  }
  _setIsMobile(_evt) {
    this._isMobile = _evt.matches;
  }
  _getActionGroup(icon, pageType, tip) {
    const sizeClass = this.showRefineSelection ? "w-1-3" : "w-1-2";
    return html`<calcite-action-group class=${safeClassMap(sizeClass)} layout=horizontal><div class="background-override"><calcite-action .active=${this._pageType === pageType} alignment=center appearance=solid class="width-full height-full" .icon=${icon} id=${icon ?? nothing} @click=${() => {
      this._setPageType(pageType);
    }} text></calcite-action></div><calcite-tooltip label placement=bottom .referenceElement=${icon}><span>${tip}</span></calcite-tooltip></calcite-action-group>`;
  }
  _setPageType(pageType) {
    this._pageType = pageType;
  }
  _getPage(pageType) {
    let page;
    switch (pageType) {
      case "LIST":
        page = this._getListPage();
        break;
      case "SELECT":
        page = this._getSelectPage();
        break;
      case "EXPORT":
        page = this._getExportPage();
        break;
      case "REFINE":
        page = this._getRefinePage();
        break;
    }
    return page;
  }
  _getListPage() {
    const hasSets = this._hasSelections();
    const noticeMessage = hasSets ? this._translations.listHasSetsTip : this.initialNotice !== "" ? this.initialNotice : this._translations.selectLayerAndAdd;
    return html`<calcite-panel>${this._getLabel(this._translations.myLists)}${this._getNotice(noticeMessage || "", "padding-sides-1 padding-bottom-1", "word-wrap-anywhere")}${hasSets ? this._getSelectionSetList() : this._getOnboardingImage()}<div class="display-flex padding-1"><calcite-button @click=${() => {
      this._setPageType("SELECT");
    }} width=full><span class="font-weight-500">${this._translations.add}</span></calcite-button></div></calcite-panel>`;
  }
  _getOnboardingImage() {
    return html`<div class="display-flex padding-sides-1"><img class="img-container" role=presentation src=${this._onboardingImageUrl ?? nothing}></div>`;
  }
  _getSelectionSetList() {
    return html`<div class="padding-top-1-2 padding-bottom-1-2"><calcite-list class="list-border margin-sides-1" label>${this._selectionSets.reduce((prev, cur, i) => {
      const ids = this._getSelectionSetIds(cur);
      let validSet = true;
      if (cur.workflowType === "REFINE") {
        const numIds = Object.keys(cur.refineInfos).reduce((_prev, _cur) => {
          const refineInfo = cur.refineInfos[_cur];
          _prev += refineInfo.addIds.length + refineInfo.removeIds.length;
          return _prev;
        }, 0);
        validSet = numIds > 0;
      }
      if (validSet) {
        prev.push(html`<calcite-list-item .label=${cur.label} @click=${() => this.mapView && this._gotoSelection(cur, this.mapView)}><div slot=content><div class="list-label">${cur.label}</div><div class="list-description">${cur?.layerView?.layer.title}</div><div class="list-description">${this._translations.selectedFeatures.replace("{{n}}", ids.length.toString())}</div></div>${this._getAction(true, "pencil", "", (_evt) => this._openSelection(cur, _evt), false, "actions-end")}${this._getAction(true, "x", "", (_evt) => this._deleteSelection(i, _evt), false, "actions-end")}</calcite-list-item>`);
      }
      return prev;
    }, [])}</calcite-list></div>`;
  }
  _getSelectionSetIds(selectionSet) {
    return selectionSet.workflowType !== "REFINE" ? selectionSet.selectedIds : Object.keys(selectionSet.refineInfos).reduce((p, c) => [...p, ...selectionSet.refineInfos[c].addIds], []);
  }
  _hasSelections(validateRefineSet = false) {
    let ids = [];
    const hasRefineSet = this._selectionSets.some((ss) => {
      if (ss.workflowType === "REFINE") {
        ids = this._getSelectionSetIds(ss);
        return true;
      } else {
        return false;
      }
    });
    return validateRefineSet && hasRefineSet ? ids.length > 0 || this._selectionSets.length > 1 : this._selectionSets.length > 0;
  }
  async _getNumDuplicates() {
    const exportInfos = this._getExportInfos();
    const labels = this.mapView?.map && await consolidateLabels(this.mapView.map, exportInfos);
    const duplicatesRemoved = labels && removeDuplicateLabels(labels);
    return labels && duplicatesRemoved ? labels.length - duplicatesRemoved.length : 0;
  }
  _getExportInfos() {
    return this._selectionSets.reduce((prev, cur) => {
      if (cur.download) {
        if (cur.workflowType !== "REFINE" && cur?.layerView) {
          const id = cur.layerView.layer.id;
          if (id !== void 0) {
            this._updateIds(id, cur.layerView, cur.selectedIds, prev);
          }
        } else {
          Object.keys(cur.refineInfos).forEach((k) => {
            const refineIds = cur.refineInfos[k];
            if (refineIds.addIds.length > 0) {
              this._updateIds(k, refineIds.layerView, refineIds.addIds, prev);
            }
          });
        }
      }
      return prev;
    }, {});
  }
  _updateIds(id, layerView, ids, obj) {
    if (obj[id]) {
      obj[id].ids = obj[id].ids.concat(ids);
    } else {
      obj[id] = {
        layerView,
        ids
      };
    }
    return obj;
  }
  _getSelectPage() {
    const noticeText = this._translations.selectSearchTip;
    return html`<calcite-panel>${this._getLabel(this._translations?.stepTwoFull, true)}${this._getNotice(noticeText, "padding-1", "word-wrap-anywhere")}<div><map-select-tools .bufferColor=${this.bufferColor} .bufferOutlineColor=${this.bufferOutlineColor} class="font-bold" .customLabelEnabled=${this.customLabelEnabled} .defaultBufferDistance=${this.defaultBufferDistance} .defaultBufferUnit=${this.defaultBufferUnit} .enableLayerFeatures=${this.enableLayerFeatures} .enableLayerFeaturesOnLoad=${this.enableLayerFeaturesOnLoad} .enableSearchDistance=${this.enableSearchDistance} .enableSearchDistanceOnLoad=${this.enableSearchDistanceOnLoad} .enableSketchTools=${this.enableSketchTools} .enabledLayerIds=${this.addresseeLayerIds} .isUpdate=${!!this._activeSelection} .mapView=${this.mapView} .noResultText=${this.noResultText} @selectionSetChange=${this._updateForSelection} .searchConfiguration=${this._searchConfiguration} .searchDistanceEnabled=${this.enableSearchDistanceOnLoad} .selectionLayerIds=${this.selectionLayerIds} .selectionSet=${this._activeSelection} .sketchLineSymbol=${this.sketchLineSymbol} .sketchPointSymbol=${this.sketchPointSymbol} .sketchPolygonSymbol=${this.sketchPolygonSymbol} .useLayerFeaturesEnabled=${this.enableLayerFeaturesOnLoad} ${ref(this._selectTools)}></map-select-tools></div>${this._getPageNavButtons(this._translations.done, this._numSelected === 0, () => {
      void this._saveSelection();
    }, this._translations.cancel, false, () => {
      void this._home();
    })}</calcite-panel>`;
  }
  _getExportPage() {
    const hasSelections = this._hasSelections(this.showRefineSelection);
    const displayDuplicatesClass = this._numDuplicates > 0 ? "display-block" : "display-none";
    return html`<calcite-panel><div>${this._getLabel(this._translations.export, false)}${hasSelections ? html`<div>${this._getNotice(this._translations.exportTip, "padding-sides-1")}${this._getLabel(this._translations.exportListsLabel)}${this._getExportSelectionLists()}<div class=${`padding-sides-1 ${displayDuplicatesClass}`}><div class="display-flex"><calcite-label layout=inline><calcite-checkbox ${ref(this._removeDuplicates)}></calcite-checkbox><div class="display-flex">${this._translations.removeDuplicate}<div class="info-message padding-start-1-2"><calcite-input-message class="info-blue margin-top-0" scale=m>${` ${this._translations.numDuplicates.replace("{{n}}", this._numDuplicates.toString())}`}</calcite-input-message></div></div></calcite-label><calcite-icon class="padding-start-1-2 icon" .flipRtl=${!(this._translations._lang?.toLowerCase() === "he")} icon=question id=remove-duplicates-icon scale=s></calcite-icon></div><calcite-popover closable label overlay-positioning=fixed reference-element=remove-duplicates-icon><span class="tooltip-message">${this._translations.duplicatesTip}</span></calcite-popover></div><div class="border-bottom"></div><div class="padding-top-sides-1"><calcite-segmented-control class="w-100" @calciteSegmentedControlChange=${this._exportTypeChange} width=full><calcite-segmented-control-item .checked=${this._exportType === "PDF"} class="w-50 end-border" value=PDF><span class="font-weight-500">${this._translations.pdf}</span></calcite-segmented-control-item><calcite-segmented-control-item .checked=${this._exportType === "CSV"} class="w-50" value=CSV><span class="font-weight-500">${this._translations.csv}</span></calcite-segmented-control-item></calcite-segmented-control></div><div class="padding-bottom-1">${this._getExportOptions()}</div><div class="padding-1 display-flex"><calcite-button .disabled=${!this._downloadActive || this._fetchingData || !this._addMap && !this._addResults} .loading=${this._fetchingData} @click=${() => void this._export()} width=full><span class="font-weight-500">${this._translations.export}</span></calcite-button></div></div>` : this._getNotice(this._translations.downloadNoLists, "padding-sides-1 padding-bottom-1")}</div></calcite-panel>`;
  }
  _exportTypeChange(_evt) {
    this._exportType = _evt.target.value;
  }
  _getExportOptions() {
    const displayClass = this._exportType === "PDF" ? "display-block" : "display-none";
    const titleOptionsClass = this._addTitle ? "display-block" : "display-none";
    const graphicsOptionsClass = this._addMap ? "display-flex" : "display-none";
    const title = this._titleValue ? this._titleValue : this.defaultExportTitle ? this.defaultExportTitle : "";
    const formatOptionsClass = this._addResults ? "" : "display-none";
    return html`<div class=${safeClassMap(displayClass)}>${this._getLabel(this._translations.pdfOptions, true)}<div class="padding-top-sides-1"><calcite-label class="label-margin-0" layout=inline><calcite-checkbox .checked=${this._addResults} @calciteCheckboxChange=${() => this._addResults = !this._addResults}></calcite-checkbox>${this._translations.addResults}</calcite-label></div><div class=${`padding-top-sides-1 ${formatOptionsClass}`}><calcite-label class="label-margin-0">${this._translations.selectPDFLabelOption}</calcite-label></div><div class=${`padding-sides-1 ${formatOptionsClass}`}><pdf-download .defaultNumLabelsPerPage=${Number.parseInt(this.defaultNumLabelsPerPage.toString(), 10)} .disabled=${!this._downloadActive} ${ref(this._downloadTools)}></pdf-download></div><div class="padding-top-sides-1"><calcite-label class="label-margin-0" layout=inline><calcite-checkbox .checked=${this._addTitle} @calciteCheckboxChange=${() => this._addTitle = !this._addTitle}></calcite-checkbox>${this._translations.title}</calcite-label></div><div class=${safeClassMap(titleOptionsClass)}>${this._getLabel(this._translations.title, true, "")}<calcite-input-text class="padding-sides-1" @calciteInputTextInput=${() => this._changeTitle()} .placeholder=${this._translations.titlePlaceholder} .value=${title} ${ref(this._titleElement)}></calcite-input-text></div><div class="padding-top-sides-1"><calcite-label class="label-margin-0" layout=inline><calcite-checkbox .checked=${this._addMap} @calciteCheckboxChange=${() => this._handleAddMapChange()}></calcite-checkbox>${this._translations.includeMap}</calcite-label></div><div class=${`padding-top-sides-1 ${graphicsOptionsClass}`}><calcite-label class="label-margin-0" layout=inline><calcite-checkbox .checked=${this._exportGraphics} @calciteCheckboxChange=${() => this._handleExportGraphicsChange()}></calcite-checkbox>${this._translations.listGraphics}</calcite-label><calcite-icon class="padding-start-1-2 icon" .flipRtl=${!(this._translations._lang?.toLowerCase() === "he")} icon=question id=list-graphics-icon scale=s></calcite-icon><calcite-popover closable label overlay-positioning=fixed reference-element=list-graphics-icon><span class="tooltip-message">${this._translations.listGraphicsTip}</span></calcite-popover></div></div>`;
  }
  _handleAddMapChange() {
    this._addMap = !this._addMap;
    this._updateExportGraphics();
  }
  _handleExportGraphicsChange() {
    this._exportGraphics = !this._exportGraphics;
    this._updateExportGraphics();
  }
  _getManagedLayer(type) {
    let layer = void 0;
    const _state = this._pnStateContextProvider.value;
    Object.keys(_state.managedLayers).some((k) => {
      const i = this.mapView?.map.layers.findIndex((l) => l.title === k);
      if (_state.managedLayers[k] === type && i !== void 0) {
        layer = this.mapView?.map.layers.getItemAt(i);
        return true;
      } else {
        return false;
      }
    });
    return layer;
  }
  _updateExportGraphics(clear = false) {
    if (clear || !this._exportGraphics || !this._addMap) {
      this._removeExportGraphics();
    }
    if (this._exportGraphics && this._addMap) {
      this._addExportGraphics();
    }
  }
  _removeExportGraphics() {
    const sketchLayer = this._getManagedLayer("sketch");
    const bufferLayer = this._getManagedLayer("buffer");
    if (sketchLayer) {
      sketchLayer.graphics.removeAll();
    }
    if (bufferLayer) {
      bufferLayer.graphics.removeAll();
    }
  }
  _addExportGraphics() {
    const sketchLayer = this._getManagedLayer("sketch");
    const bufferLayer = this._getManagedLayer("buffer");
    this._refineGraphics.forEach((obj) => {
      sketchLayer?.add(obj.drawnGraphics);
      bufferLayer?.add(obj.bufferGraphics);
    });
    this._selectionSets.forEach((ss) => {
      if (ss.download) {
        if (sketchLayer && ss.sketchGraphic) {
          sketchLayer.graphics.add(ss.sketchGraphic);
        }
        if (bufferLayer) {
          const symbol = {
            type: "simple-fill",
            color: this.bufferColor,
            outline: {
              color: this.bufferOutlineColor,
              width: 1
            }
          };
          const bufferGraphic = new Graphic({
            geometry: ss.buffer,
            symbol
          });
          if (bufferGraphic) {
            bufferLayer.graphics.add(bufferGraphic);
          }
        }
      }
    });
  }
  _getRefinePage() {
    const hasSelections = this._hasSelections();
    return html`<calcite-panel>${this._getLabel(this._translations.refineSelection)}${hasSelections ? html`<div>${this._getNotice(this._translations.refineTip, "padding-sides-1")}<refine-selection .enabledLayerIds=${this.selectionLayerIds} .mapView=${this.mapView} .drawnGraphicsArr=${this._refineGraphics} .selectionSets=${this._selectionSets} .sketchLineSymbol=${this.sketchLineSymbol} .sketchPointSymbol=${this.sketchPointSymbol} .sketchPolygonSymbol=${this.sketchPolygonSymbol} .bufferColor=${this.bufferColor} .bufferOutlineColor=${this.bufferOutlineColor} .defaultBufferDistance=${this.defaultBufferDistance} .defaultBufferUnit=${this.defaultBufferUnit} .enableSearchDistance=${this.enableSearchDistance} .enableSearchDistanceOnLoad=${this.enableSearchDistanceOnLoad} .searchDistanceEnabled=${this.enableSearchDistanceOnLoad} ${ref(this._refineSelection)}></refine-selection></div>` : this._getNotice(this._translations.refineTipNoSelections, "padding-sides-1")}</calcite-panel>`;
  }
  _getPageNavButtons(topLabel, topDisabled, topFunc, bottomLabel, bottomDisabled, bottomFunc) {
    return html`<div class="padding-bottom-1"><div class="display-flex padding-top-sides-1"><calcite-button .disabled=${topDisabled} @click=${topFunc} width=full><span class="font-weight-500">${topLabel}</span></calcite-button></div><div class="display-flex padding-top-1-2 padding-sides-1"><calcite-button appearance=outline .disabled=${bottomDisabled} @click=${bottomFunc} width=full><span class="font-weight-500">${bottomLabel}</span></calcite-button></div></div>`;
  }
  _changeTitle() {
    if (this._titleElement.value?.value) {
      this._titleValue = this._titleElement.value.value || "";
    }
  }
  _getNotice(message, noticeClass = "padding-1", messageClass = "") {
    return html`<calcite-notice class=${safeClassMap(noticeClass)} icon=lightbulb kind=success open><div class=${safeClassMap(messageClass)} slot=message>${message}</div></calcite-notice>`;
  }
  _getLabel(label, disableSpacing = false, labelClass = "font-bold") {
    labelClass += disableSpacing ? " label-margin-0" : "";
    return html`<div class=padding-top-sides-1><calcite-label class=${safeClassMap(labelClass)}>${label}</calcite-label></div>`;
  }
  _getExportSelectionLists() {
    return this._selectionSets.reduce((prev, cur) => {
      const ids = this._getSelectionSetIds(cur);
      const validSet = cur.workflowType !== "REFINE" || ids.length > 0;
      if (!this._downloadActive && cur.download && validSet) {
        this._downloadActive = true;
      }
      if (validSet) {
        prev.push(html`<div class="display-flex padding-sides-1 padding-bottom-1"><calcite-checkbox .checked=${cur.download} class="align-center" @calciteCheckboxChange=${() => {
          void this._toggleDownload(cur.id);
        }}></calcite-checkbox><calcite-list class="list-border margin-start-1-2 width-full" id=download-list label><calcite-list-item .disabled=${!cur.download} .label=${cur.label} @click=${() => {
          void this._toggleDownload(cur.id);
        }}><div slot=content><div class="list-label">${cur.label}</div><div class="list-description">${cur?.layerView?.layer.title}</div><div class="list-description">${this._translations.selectedFeatures.replace("{{n}}", ids.length.toString())}</div></div></calcite-list-item></calcite-list></div>`);
      }
      return prev;
    }, []) || html`<div></div>`;
  }
  async _toggleDownload(id) {
    let isActive = false;
    this._selectionSets = this._selectionSets.map((ss) => {
      ss.download = ss.id === id ? !ss.download : ss.download;
      isActive = ss.download ? true : isActive;
      return ss;
    });
    this._updateExportGraphics(true);
    this._downloadActive = isActive;
    this._fetchingData = true;
    this._numDuplicates = await this._getNumDuplicates();
    this._fetchingData = false;
    await this._highlightFeatures();
  }
  async _export() {
    const exportInfos = this._addResults ? this._getSelectionIdsAndViews(this._selectionSets, true) : {};
    if (this._exportType === "PDF") {
      let initialImageDataUrl = "";
      if (this._addMap && this.mapView) {
        const screenshot = await this.mapView.takeScreenshot({ width: 1500, height: 2e3 });
        initialImageDataUrl = screenshot?.dataUrl;
      }
      this._fetchingData = true;
      this._downloadTools.value && this._removeDuplicates.value && this.mapView?.map && await this._downloadTools.value.downloadPDF(this.mapView.map, exportInfos, this._removeDuplicates.value.checked, this._addTitle && this._titleElement.value ? this._titleElement.value.value : "", initialImageDataUrl);
      this._fetchingData = false;
    }
    if (this._exportType === "CSV") {
      this._fetchingData = true;
      this._downloadTools.value && this.mapView?.map && await this._downloadTools.value.downloadCSV(this.mapView.map, exportInfos, this._removeDuplicates.value?.checked || false);
      this._fetchingData = false;
    }
  }
  _getSelectionIdsAndViews(selectionSets, downloadSetsOnly = false) {
    const exportSelectionSets = downloadSetsOnly ? selectionSets.filter((ss) => ss.download) : selectionSets;
    return exportSelectionSets.reduce((prev, cur) => {
      if (cur.workflowType === "REFINE") {
        Object.keys(cur.refineInfos).forEach((k) => {
          const refineInfo = cur.refineInfos[k];
          if (refineInfo.addIds) {
            const _id = refineInfo.layerView.layer.id;
            prev = this._updateExportInfos(prev, _id, cur.label, refineInfo.addIds, refineInfo.layerView);
          }
        });
      } else {
        const id = cur?.layerView?.layer.id;
        if (id !== void 0 && cur.layerView) {
          prev = this._updateExportInfos(prev, id, cur.label, cur.selectedIds, cur.layerView);
        }
      }
      return prev;
    }, {});
  }
  _updateExportInfos(exportInfos, id, label, newIds, layerView) {
    if (id && Object.keys(exportInfos).indexOf(id) > -1) {
      exportInfos[id].ids = [.../* @__PURE__ */ new Set([...exportInfos[id].ids, ...newIds])];
      exportInfos[id].selectionSetNames.push(label);
    } else if (id) {
      exportInfos[id] = {
        ids: newIds,
        layerView,
        selectionSetNames: [label]
      };
    }
    return exportInfos;
  }
  _getAction(enabled, icon, text, onClick, indicator = false, slot = "") {
    return html`<calcite-action appearance=solid .disabled=${!enabled} .icon=${icon} icon-flip-rtl .indicator=${indicator} @click=${onClick} slot=${slot ?? nothing} .text=${text}></calcite-action>`;
  }
  _updateForSelection(_evt) {
    this._numSelected = _evt.detail;
    this._saveEnabled = this._numSelected > 0;
  }
  async _home() {
    await this._clearSelection();
    this._setPageType("LIST");
  }
  async _saveSelection() {
    const results = await this._selectTools.value?.getSelection();
    if (results) {
      const isUpdate = this._selectTools.value?.isUpdate;
      this._selectionSets = isUpdate ? this._selectionSets.map((ss) => {
        return ss.id === results.id ? results : ss;
      }) : [...this._selectionSets, results];
    }
    return this._home();
  }
  async _clearSelection() {
    await this._selectTools.value?.clearSelection();
    this._numSelected = 0;
    this._activeSelection = void 0;
  }
  async _deleteSelection(index, _evt) {
    _evt.stopPropagation();
    this._selectionSets = this._selectionSets.filter((ss, i) => {
      if (ss.workflowType === "REFINE") {
        this._refineGraphics = [];
      }
      if (i !== index) {
        return ss;
      } else {
        return false;
      }
    });
    return this._highlightFeatures();
  }
  _gotoSelection(selSet, mapView) {
    if (selSet.selectedIds && selSet.layerView) {
      void goToSelection(selSet.selectedIds, selSet.layerView, mapView, this.featureHighlightEnabled, this.featureEffect);
    }
  }
  _openSelection(selectionSet, _evt) {
    _evt.stopPropagation();
    this._activeSelection = selectionSet;
    this._pageType = selectionSet.workflowType === "REFINE" ? "REFINE" : "SELECT";
  }
  async _highlightFeatures() {
    const _state = this._pnStateContextProvider.value;
    this._clearHighlight();
    const idSets = this._getSelectionIdsAndViews(this._selectionSets, this._pageType === "EXPORT");
    const idKeys = Object.keys(idSets);
    if (idKeys.length > 0) {
      for (let i = 0; i < idKeys.length; i++) {
        const idSet = idSets[idKeys[i]];
        if (idSet.layerView && this.mapView) {
          const handle = await highlightFeatures(idSet.ids, idSet.layerView, this.mapView);
          _state.highlightHandles.push(handle);
        }
      }
    }
  }
  _checkPopups() {
    if (typeof this._popupsEnabled !== "boolean") {
      this._popupsEnabled = this.mapView?.popupEnabled ? true : false;
    }
  }
  _clearHighlight() {
    const _state = this._pnStateContextProvider.value;
    if (_state && _state.highlightHandles) {
      _state.removeHandles();
    }
  }
}
customElement("public-notification", PublicNotification);
export {
  PublicNotification
};
