/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { g as G, c as U } from "../../chunks/runtime.js";
import { e as H, h as j } from "../../chunks/mapViewUtils.js";
import { c as B, r as J, b as W, e as z } from "../../chunks/downloadUtils.js";
import { u as q } from "../../chunks/useT9n.js";
import { css as X, html as l, nothing as k } from "lit";
import { createRef as v, ref as _ } from "lit-html/directives/ref.js";
import { LitElement as Y, createEvent as Q, noShadowRoot as K, safeClassMap as x, safeStyleMap as Z } from "@arcgis/lumina";
import { p as ee } from "../../chunks/publicNotificationContext.js";
import { useContextProvider as te } from "@arcgis/lumina/context";
import "../refine-selection/customElement.js";
import ie from "@arcgis/core/Graphic.js";
import { Controller as se } from "@arcgis/lumina/controllers";
import ae from "@arcgis/core/rest/support/PrintTemplate.js";
import oe from "@arcgis/core/rest/support/PrintParameters.js";
import * as le from "@arcgis/core/rest/print.js";
import * as V from "@arcgis/core/rest/geoprocessor.js";
import P from "@arcgis/core/request.js";
const ne = X`@layer{: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-bottom-0{padding-bottom:0!important}.padding-inline-start-0{padding-inline-start:0!important}.padding-top-sides-1{padding-block-start:1rem;padding-inline-start:1rem;padding-inline-end:1rem}.padding-block-start-1{padding-block-start:1rem}.padding-sides-1{padding-inline-start:1rem;padding-inline-end:1rem}.padding-top-1-2{padding-block-start:.5rem!important}.padding-top-1{padding-top:1rem}.indent-group{border-inline-start:1px solid var(--calcite-color-border-2);margin-bottom:.5rem;padding-inline-start:1rem;margin-inline-start:.5rem}.margin-bottom-0-5{margin-bottom:.5rem}.margin-top-0-5{margin-top:.5rem!important}.instructional-text{line-height:1;padding:0!important;margin:0;color:var(--calcite-color-text-2);font-size:var(--calcite-font-size--2)}.info-blue{color:var(--calcite-color-status-info)}.info-message{justify-content:center;display:grid}.font-bold{font-weight:700}.header-label{font-weight:700;font-size:var(--calcite-font-size-0)}.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:.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:.5rem}.margin-top-0{margin-block-start:0!important}.margin-top-1{margin-top:1rem!important}.label-margin-0{--calcite-label-margin-bottom: 0}.list-label{color:var(--calcite-color-text-1);font-weight:var(--calcite-font-weight-bold)!important}.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:.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-surface-4: var(--calcite-color-brand);--calcite-color-surface-3: var(--calcite-color-brand-hover);--calcite-color-text-1: var(--calcite-color-text-inverse);--calcite-action-background-color-hover: var(--calcite-color-brand-hover)}.padding-bottom-1{padding-bottom:1rem}.word-wrap-anywhere{word-wrap:anywhere}.list-container{padding:0 1rem 1rem}.list-items{align-items:center;background-color:#fff;box-shadow:0 1px 3px #0000001a;font-family:sans-serif;padding:12px 16px}.list-item{display:flex;align-items:center;justify-content:space-between}.item-label{color:#4a4a4a;font-size:16px}.tooltip-message{padding:5px 8px;font-weight:var(--calcite-font-weight-normal);color:var(--calcite-color-text-2);max-width:400px}calcite-segmented-control{--calcite-segmented-control-border-color: var(--calcite-color-border-2)}calcite-segmented-control-item{--calcite-segmented-control-color: var(--calcite-color-text-3)}calcite-segmented-control-item[checked]{--calcite-segmented-control-border-color: var(--calcite-color-surface-highlight);--calcite-segmented-control-background-color: var(--calcite-color-surface-highlight);--calcite-segmented-control-color: var(--calcite-color-text-highlight)}calcite-action-bar{--calcite-internal-action-bar-gap: 0px;--calcite-internal-action-bar-padding: 0px}}`;
class re extends se {
  constructor() {
    super(), this.managedLayers = {}, this.managedTables = [], this.highlightHandles = [];
  }
  // remove all handles
  removeHandles() {
    this.highlightHandles.forEach((e) => {
      e?.remove();
    }), this.highlightHandles = [];
  }
}
class ce extends Y {
  constructor() {
    super(), this.addresseeLayerIds = [], this.bufferColor = [227, 139, 79, 0.8], this.bufferOutlineColor = [255, 255, 255], this.customLabelEnabled = !1, this.customExport = !1, this.customExportURL = "", this.defaultBufferDistance = 0, this.defaultBufferUnit = "feet", this.defaultExportTitle = "", this.defaultNumLabelsPerPage = 6, this.enableLayerFeatures = !0, this.enableLayerFeaturesOnLoad = !1, this.enableSearchDistance = !0, this.enableSearchDistanceOnLoad = !1, this.enableSketchTools = !0, this.featureHighlightEnabled = !1, this.noResultText = "", this.initialNotice = "", this.selectionLayerIds = [], this.showRefineSelection = !1, this.showSearchSettings = !0, this._exportGraphics = !1, this._addMap = !1, this._addResults = !0, this._addTitle = !1, this._downloadActive = !0, this._exportType = "PDF", this._fetchingData = !1, this._isMobile = !1, this._numDuplicates = 0, this._pageType = "LIST", this._saveEnabled = !1, this._selectionSets = [], this._segmentType = "STANDARD", this._selectedReportingLayerId = "", this._isInitialLoading = !0, this._layoutTemplates = [], this._translations = q({ name: "public-notification", blocking: !0 }), this._downloadTools = v(), this.layoutTemplateSelectRef = v(), this.reportTemplateSelectRef = v(), this._onboardingImageUrl = "", this._popupsEnabled = !1, this._removeDuplicates = v(), this._selectTools = v(), this._refineSelection = v(), this._titleElement = v(), this._titleValue = void 0, this._numSelected = 0, this._pnStateContextProvider = te({ context: ee }), this._refineGraphics = [], this._reportTemplates = [], this._reportTemplatesInfo = [], this.searchConfigurationChange = Q(), this.listenOn(window, "selectionSetsChanged", this.selectionSetsChanged), this._pnState = new re(), this._pnStateContextProvider.setValue(this._pnState);
  }
  static {
    this.properties = { addresseeLayerIds: 0, bufferColor: 1, bufferOutlineColor: 1, customLabelEnabled: 5, customExport: 5, customExportURL: 1, defaultBufferDistance: 9, defaultBufferUnit: 1, defaultExportTitle: 1, defaultNumLabelsPerPage: 9, enableLayerFeatures: 5, enableLayerFeaturesOnLoad: 5, enableSearchDistance: 5, enableSearchDistanceOnLoad: 5, enableSketchTools: 5, featureEffect: 0, featureHighlightEnabled: 5, mapView: 0, noResultText: 1, initialNotice: 1, searchConfiguration: 0, selectionLayerIds: 0, showRefineSelection: 5, showSearchSettings: 5, sketchLineSymbol: 0, sketchPointSymbol: 0, sketchPolygonSymbol: 0, _exportGraphics: 16, _addMap: 16, _addResults: 16, _addTitle: 16, _downloadActive: 16, _exportType: 16, _fetchingData: 16, _isMobile: 16, _numDuplicates: 16, _pageType: 16, _saveEnabled: 16, _selectionSets: 16, _segmentType: 16, _selectedReportingLayerId: 16, _isInitialLoading: 16, _layoutTemplates: 16, _translations: 16 };
  }
  static {
    this.styles = ne;
  }
  static {
    this.shadowRootOptions = K;
  }
  willUpdate(e) {
    e.has("mapView") && this.mapView && this.mapViewWatchHandler(this.mapView), e.has("searchConfiguration") && this.searchConfiguration && this.watchSearchConfigurationHandler(this.searchConfiguration, e.get("searchConfiguration")), e.has("sketchLineSymbol") && this.sketchLineSymbolWatchHandler(this.sketchLineSymbol, e.get("sketchLineSymbol")), e.has("sketchPointSymbol") && this.sketchPointSymbolWatchHandler(this.sketchPointSymbol, e.get("sketchPointSymbol")), e.has("sketchPolygonSymbol") && this.sketchPolygonSymbolWatchHandler(this.sketchPolygonSymbol, e.get("sketchPolygonSymbol")), e.has("_pageType") && (this.hasUpdated || this._pageType !== "LIST") && this.pageTypeWatchHandler(this._pageType, e.get("_pageType")), (e.has("customExport") || e.has("customExportURL")) && this.hasUpdated && this._setTemplates();
  }
  async mapViewWatchHandler(e) {
    e?.popup && (this._popupsEnabled = e?.popupEnabled), this.searchConfiguration && this._initSearchConfiguration(this.searchConfiguration);
  }
  async watchSearchConfigurationHandler(e, t) {
    const i = JSON.stringify(e);
    this.mapView && (i !== JSON.stringify(t) || i && !this._searchConfiguration) && (this._searchConfiguration = JSON.parse(i), this._searchConfiguration && this.searchConfigurationChange.emit(this._searchConfiguration), this._home());
  }
  async sketchLineSymbolWatchHandler(e, t) {
    e && JSON.stringify(e) !== JSON.stringify(t) && this._setLineSymbol(e);
  }
  async sketchPointSymbolWatchHandler(e, t) {
    e && JSON.stringify(e) !== JSON.stringify(t) && this._setPointSymbol(e);
  }
  async sketchPolygonSymbolWatchHandler(e, t) {
    e && JSON.stringify(e) !== JSON.stringify(t) && this._setPolygonSymbol(e);
  }
  async pageTypeWatchHandler(e, t) {
    if (this._checkPopups(), this.mapView?.popup && (this.mapView.popupEnabled = e !== "LIST" ? !1 : this._popupsEnabled), e === "EXPORT" && (this._fetchingData = !0, this._numDuplicates = await this._getNumDuplicates(), this._updateExportGraphics(), this._fetchingData = !1), this._clearHighlight(), (t === "SELECT" || t === "REFINE") && await this._clearSelection(), t === "EXPORT" && this._removeExportGraphics(), e !== "SELECT")
      return this._highlightFeatures();
  }
  selectionSetsChanged(e) {
    this._selectionSets = [...e.detail];
  }
  connectedCallback() {
    super.connectedCallback(), this._mediaQuery = window.matchMedia("(max-width: 600px)"), this.listenOn(this._mediaQuery, "change", (e) => this._setIsMobile(e));
  }
  async load() {
    this._initSymbols(), this._onboardingImageUrl = G("assets/public-notification/images/onboarding.png");
  }
  render() {
    const e = this._isMobile ? "footer" : "header";
    return l`<calcite-shell>${this._isInitialLoading ? l`<calcite-loader label></calcite-loader>` : l`<calcite-action-bar class="border-bottom-1 action-bar-size" expand-disabled layout=horizontal slot=${e ?? k}>${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>`;
  }
  async loaded() {
    this.searchConfiguration && this._initSearchConfiguration(this.searchConfiguration), this.customExport && this.customExportURL && await this._setTemplates(), this._isInitialLoading = !1;
  }
  _initSearchConfiguration(e) {
    this.searchConfiguration && !this._searchConfiguration && this.mapView && (this._searchConfiguration = e, this.searchConfigurationChange.emit(this._searchConfiguration), this._home());
  }
  _initSymbols() {
    this._setLineSymbol(this.sketchLineSymbol), this._setPointSymbol(this.sketchPointSymbol), this._setPolygonSymbol(this.sketchPolygonSymbol);
  }
  _setLineSymbol(e) {
    const t = e?.type === "simple-line";
    this.sketchLineSymbol = t ? e : this._jsonUtils?.fromJSON(e || {
      type: "esriSLS",
      color: [130, 130, 130, 255],
      width: 2,
      style: "esriSLSSolid"
    });
  }
  _setPointSymbol(e) {
    const t = e?.type === "simple-marker";
    this.sketchPointSymbol = t ? e : this._jsonUtils?.fromJSON(e || {
      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(e) {
    const t = e?.type === "simple-fill";
    this.sketchPolygonSymbol = t ? e : this._jsonUtils?.fromJSON(e || {
      type: "esriSFS",
      color: [150, 150, 150, 51],
      outline: {
        type: "esriSLS",
        color: [50, 50, 50, 255],
        width: 2,
        style: "esriSLSSolid"
      },
      style: "esriSFSSolid"
    });
  }
  _setIsMobile(e) {
    this._isMobile = e.matches;
  }
  _getActionGroup(e, t, i) {
    const s = this.showRefineSelection ? "w-1-3" : "w-1-2";
    return l`<calcite-action-group class=${x(s)} layout=horizontal><div class="background-override"><calcite-action .active=${this._pageType === t} alignment=center class="width-full height-full" .icon=${e} id=${e ?? k} @click=${() => {
      this._setPageType(t);
    }} style=${Z(this._pageType === t ? "background-color: var(--calcite-color-brand)" : "")} .text=${i}></calcite-action></div><calcite-tooltip placement=bottom .referenceElement=${e}><span>${i}</span></calcite-tooltip></calcite-action-group>`;
  }
  _setPageType(e) {
    this._pageType = e;
  }
  _getPage(e) {
    let t;
    switch (e) {
      case "LIST":
        t = this._getListPage();
        break;
      case "SELECT":
        t = this._getSelectPage();
        break;
      case "EXPORT":
        t = this._getExportPage();
        break;
      case "REFINE":
        t = this._getRefinePage();
        break;
    }
    return t;
  }
  _getListPage() {
    const e = this._hasSelections(), t = e ? this._translations.listHasSetsTip : this.initialNotice !== "" ? this.initialNotice : this._translations.selectLayerAndAdd;
    return l`<calcite-panel>${this._getLabel(this._translations.myLists, !1, "header-label")}${this._getNotice(t || "", "padding-sides-1 padding-bottom-1", "word-wrap-anywhere")}${e ? 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 l`<div class="display-flex padding-sides-1"><img alt aria-hidden=true class="img-container" src=${this._onboardingImageUrl ?? k}></div>`;
  }
  _getSelectionSetList() {
    return l`<div class="padding-bottom-1-2"><calcite-list class="list-border margin-sides-1" label>${this._selectionSets.reduce((e, t, i) => {
      const s = this._getSelectionSetIds(t);
      let a = !0;
      return t.workflowType === "REFINE" && (a = Object.keys(t.refineInfos).reduce((n, h) => {
        const p = t.refineInfos[h];
        return n += p.addIds.length + p.removeIds.length, n;
      }, 0) > 0), a && e.push(l`<calcite-list-item .label=${t.label} @click=${() => this.mapView && this._gotoSelection(t, this.mapView)}><div slot=content><div class="list-label">${t.label}</div><div class="list-description">${t?.layerView?.layer.title}</div><div class="list-description">${this._translations.selectedFeatures.replace("{{n}}", s.length.toString())}</div></div>${this._getAction(!0, "pencil", "", (o) => this._openSelection(t, o), !1, "actions-end")}${this._getAction(!0, "x", "", (o) => this._deleteSelection(i, o), !1, "actions-end")}</calcite-list-item>`), e;
    }, [])}</calcite-list></div>`;
  }
  _getSelectionSetIds(e) {
    return e.workflowType !== "REFINE" ? e.selectedIds : Object.keys(e.refineInfos).reduce((t, i) => [...t, ...e.refineInfos[i].addIds], []);
  }
  _hasSelections(e = !1) {
    let t = [];
    const i = this._selectionSets.some((s) => s.workflowType === "REFINE" ? (t = this._getSelectionSetIds(s), !0) : !1);
    return e && i ? t.length > 0 || this._selectionSets.length > 1 : this._selectionSets.length > 0;
  }
  async _getNumDuplicates() {
    const e = this._getExportInfos(), t = this.mapView?.map && await B(this.mapView.map, e), i = t && J(t);
    return t && i ? t.length - i.length : 0;
  }
  _getExportInfos() {
    return this._selectionSets.reduce((e, t) => {
      if (t.download)
        if (t.workflowType !== "REFINE" && t?.layerView) {
          const i = t.layerView.layer.id;
          i !== void 0 && this._updateIds(i, t.layerView, t.selectedIds, e);
        } else
          Object.keys(t.refineInfos).forEach((i) => {
            const s = t.refineInfos[i];
            s.addIds.length > 0 && this._updateIds(i, s.layerView, s.addIds, e);
          });
      return e;
    }, {});
  }
  _updateIds(e, t, i, s) {
    return s[e] ? s[e].ids = s[e].ids.concat(i) : s[e] = {
      layerView: t,
      ids: i
    }, s;
  }
  _getSelectPage() {
    const e = this._translations.selectSearchTip;
    return l`<calcite-panel>${this._getLabel(this._translations?.stepTwoFull, !0, "header-label")}${this._getNotice(e, "padding-1", "word-wrap-anywhere")}<div><map-select-tools .bufferColor=${this.bufferColor} .bufferOutlineColor=${this.bufferOutlineColor} class="" .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} header-label-class .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} ${_(this._selectTools)}></map-select-tools></div>${this._getPageNavButtons(this._translations.done, this._numSelected === 0, () => {
      this._saveSelection();
    }, this._translations.cancel, !1, () => {
      this._home();
    })}</calcite-panel>`;
  }
  _getExportPage() {
    const e = this._hasSelections(this.showRefineSelection), t = this._numDuplicates > 0 ? "display-block" : "display-none", i = this.customExport && this.customExportURL && this._layoutTemplates.length;
    return l`<calcite-panel><div>${this._getLabel(this._translations.export, !1, "header-label")}${e ? l`<div>${this._getNotice(this._translations.exportTip, "padding-sides-1")}${this._getLabel(this._translations.exportListsLabel, !1, "")}${this._getExportSelectionLists()}<div class=${`padding-sides-1 ${t}`}><div class="display-flex"><calcite-label layout=inline><calcite-checkbox ${_(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 aria-hidden=true 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="segmented-controls padding-top-sides-1">${this._getLabel(this._translations.exportOptions, !0, "", "margin-bottom-0-5")}${this._getSegmentedControls()}</div>${i ? this._getCustomPrintOptions() : l`<div class="padding-1 padding-bottom-0">${this._getExportOptions()}</div>`}<div class="padding-1 display-flex"><calcite-button .disabled=${!this._downloadActive || this._fetchingData || !this._addMap && !this._addResults} .loading=${this._fetchingData} @click=${() => this._segmentType === "CUSTOM" ? this._customExport() : void this._standardExport()} 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>`;
  }
  _customExport() {
    if (!this.mapView)
      return;
    const e = this.layoutTemplateSelectRef.value ? this.layoutTemplateSelectRef.value.selectedOption.value : "", t = this.reportTemplateSelectRef.value ? this.reportTemplateSelectRef.value.selectedOption.value : "";
    this._fetchingData = !0;
    const i = this._reportTemplatesInfo.find((h) => h.reportTemplate === t), s = i ? { ...i.reportOptions } : {}, a = this._selectedReportingLayerId;
    s?.reportSectionOverrides && Object.keys(s.reportSectionOverrides).forEach((h) => {
      s.reportSectionOverrides[h].sourceId = a;
    });
    const o = new ae({
      layout: e,
      report: t,
      format: "pdf",
      layoutOptions: {
        titleText: this._titleElement.value?.value
      },
      reportOptions: s
    }), n = new oe({
      view: this.mapView,
      template: o
    });
    le.execute(this.customExportURL, n).then((h) => {
      let p = this._titleValue;
      if (!p) {
        const g = this._getSelectionIdsAndViews(this._selectionSets, !0), d = W(g);
        p = z(d);
      }
      h.url && p && this._downloadCustomPDF(h.url, p), this._fetchingData = !1;
    }).catch((h) => {
      this._fetchingData = !1, console.error(h);
    });
  }
  async _downloadCustomPDF(e, t) {
    try {
      const i = await fetch(e);
      if (!i.ok)
        throw new Error(`Failed to fetch PDF: ${i.statusText}`);
      const s = await i.blob(), a = window.URL.createObjectURL(s), o = document.createElement("a");
      o.href = a, o.download = t || "download.pdf";
      const n = document.getElementById("custom-export-div");
      n && (n.appendChild(o), o.click(), window.URL.revokeObjectURL(a), n.removeChild(o));
    } catch (i) {
      console.error("Download failed:", i);
    }
  }
  _exportTypeChange(e) {
    this._exportType = e.target.value;
  }
  _segmentTypeChange(e) {
    this._titleValue = "", this._segmentType = e.target.value;
  }
  _getSegmentedControls() {
    return this.customExport && this.customExportURL && this._layoutTemplates.length ? this._getStandardAndCustomSegmentedControl() : this._getPDFAndCSVSementedControl();
  }
  _getPDFAndCSVSementedControl() {
    return l`<calcite-segmented-control class="w-100 calcite-segments" @calciteSegmentedControlChange=${this._exportTypeChange} width=full><calcite-segmented-control-item .checked=${this._exportType === "PDF"} class="w-50 end-border" .iconStart=${this._exportType === "PDF" ? "check" : void 0} 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" .iconStart=${this._exportType === "CSV" ? "check" : void 0} value=CSV><span class="font-weight-500">${this._translations.csv}</span></calcite-segmented-control-item></calcite-segmented-control>`;
  }
  _getStandardAndCustomSegmentedControl() {
    return l`<calcite-segmented-control class="w-100 calcite-segments" @calciteSegmentedControlChange=${this._segmentTypeChange} width=full><calcite-segmented-control-item .checked=${this._segmentType === "STANDARD"} class="w-50 end-border" .iconStart=${this._segmentType === "STANDARD" ? "check" : void 0} value=STANDARD><span class="font-weight-500">${this._translations.standard}</span></calcite-segmented-control-item><calcite-segmented-control-item .checked=${this._segmentType === "CUSTOM"} class="w-50" .iconStart=${this._segmentType === "CUSTOM" ? "check" : void 0} value=CUSTOM><span class="font-weight-500">${this._translations.custom}</span></calcite-segmented-control-item></calcite-segmented-control>`;
  }
  _getCustomPrintOptions() {
    return this._segmentType === "STANDARD" ? this._getStandardExportOptions() : this._getCustomExportOptions();
  }
  _getStandardExportOptions() {
    return l`<div class="padding-1 padding-bottom-0"><calcite-label layout=inline alignment=start scale=m><calcite-radio-button .checked=${this._exportType === "PDF"} scale=m value=PDF @calciteRadioButtonChange=${this._exportTypeChange}></calcite-radio-button>${this._translations.pdf}</calcite-label><div class=indent-group>${this._getExportOptions()}</div><calcite-label layout=inline class="margin-top-1" alignment=start scale=m><calcite-radio-button .checked=${this._exportType === "CSV"} scale=m value=CSV @calciteRadioButtonChange=${this._exportTypeChange}></calcite-radio-button>${this._translations.csv}</calcite-label></div>`;
  }
  _getCustomExportOptions() {
    const e = this._titleValue ? this._titleValue : this.defaultExportTitle ? this.defaultExportTitle : "", t = [], i = this._getSelectionIdsAndViews(this._selectionSets, !0);
    return Object.keys(i).forEach((s) => {
      i[s].ids.length && t.push(s);
    }), l`<div id=custom-export-div class="padding-top-sides-1"><p class="instructional-text">${this._translations.formattingTip}</p>${t.length > 1 && l`<p class="instructional-text margin-top-0-5">${this._translations.selectMatchingInputLayersLabel}</p>` || ""}<div class=${"margin-top-1"}>${this._getLabel(this._translations.title, !0, "", "none")}<calcite-input-text class="padding-inline-start-0 padding-top-1-2" @calciteInputTextInput=${() => this._changeTitle()} .placeholder=${this._translations.titlePlaceholder} .value=${e} ${_(this._titleElement)}></calcite-input-text></div><div class=${"margin-top-1"}>${this._getLabel(this._translations.layoutTemplate, !0, "", "none")}</div><calcite-select class="padding-inline-start-0 padding-top-1-2" label ${_(this.layoutTemplateSelectRef)}>${this._layoutTemplates.map((s, a) => l`<calcite-option .selected=${a === 0} .value=${s}>${s}</calcite-option>`)}</calcite-select>${this._reportTemplates?.length && l`<div class=${"margin-top-1"}>${this._getLabel(this._translations.reportTemplate, !0, "", "none")}</div><calcite-select class="padding-inline-start-0 padding-top-1-2" label ${_(this.reportTemplateSelectRef)}>${this._reportTemplates.map((s, a) => l`<calcite-option .selected=${a === 0} .value=${s}>${s}</calcite-option>`)}</calcite-select><div class=${"padding-top-sides-1 padding-inline-start-0 display-flex margin-bottom-0-5"}><calcite-label class="label-margin-0" layout=inline>${this._translations.reportLayer}</calcite-label><calcite-icon class="padding-start-1-2 icon" .flipRtl=${this._translations._lang?.toLowerCase() !== "he"} icon=information id=filter-message-info scale=s></calcite-icon><calcite-popover closable label overlay-positioning=fixed reference-element=filter-message-info><span class="tooltip-message">${this._translations.sourceLayerWarning}</span></calcite-popover></div><map-layer-picker .disabled=${t.length <= 1} .enabledLayerIds=${t} .mapView=${this.mapView} @layerSelectionChange=${(s) => {
      this._selectedReportingLayerId = s.detail[0];
    }} .selectedIds=${[this._selectedReportingLayerId]}></map-layer-picker>` || ""}</div>`;
  }
  async _setTemplates() {
    if (!this.customExportURL || !this.customExport) {
      this.resetCustomExport();
      return;
    }
    const e = this.customExportURL, t = `${e.split("/GPServer")?.[0]}/GPServer`;
    try {
      const i = await this.getTasksInfo(t);
      let s = "";
      const a = i.tasks?.map(async (d) => {
        await this.getTaskType(d, t) === "GetReportTemplatesInfo" && (s = `${t}/${d}`);
      });
      a && await Promise.all(a), s && i.executionType && await this._fetchReportTemplates(s, i.executionType);
      const n = (await P(e, {
        authMode: "auto",
        responseType: "json",
        query: { f: "json" }
      }))?.data, h = n.parameters.find((d) => d.name === "Layout_Template" && Array.isArray(d.choiceList)), p = n.parameters.find((d) => d.name === "Report_Template" && Array.isArray(d.choiceList));
      this._layoutTemplates = h ? h.choiceList : [];
      const g = p ? p.choiceList : [];
      this._reportTemplates = this._reportTemplatesInfo.length ? g.filter((d) => this._reportTemplatesInfo.some(($) => $.reportTemplate === d)) : [];
    } catch (i) {
      this.resetCustomExport(), console.error(i);
    }
  }
  resetCustomExport() {
    this._layoutTemplates = [], this._reportTemplates = [], this._segmentType = "STANDARD";
  }
  async getTaskType(e, t) {
    if (!e || !t)
      return Promise.resolve("");
    const i = `${t}/${e}`;
    try {
      const o = (await P(i, {
        authMode: "auto",
        responseType: "json",
        query: { f: "json" }
      }))?.data?.name || "";
      return Promise.resolve(o);
    } catch (s) {
      return console.error(s), Promise.resolve("");
    }
  }
  async getTasksInfo(e) {
    if (!e)
      return Promise.resolve({});
    const t = `${e}?f=json`, i = {
      authMode: "auto",
      responseType: "json",
      query: { f: "json" }
    };
    try {
      const a = (await P(t, i))?.data, o = a?.tasks, n = a?.executionType === "esriExecutionTypeSynchronous" ? "execute" : "submitJob";
      return {
        tasks: o,
        supportedOperations: n,
        executionType: a?.executionType
      };
    } catch (s) {
      return this.resetCustomExport(), console.error(s), {};
    }
  }
  async _fetchReportTemplates(e, t) {
    if (e)
      try {
        if (t === "esriExecutionTypeSynchronous") {
          const s = (await V.execute(e, {}))?.results?.find((a) => a.paramName === "Output_JSON");
          this._reportTemplatesInfo = s?.value ?? [];
        } else {
          const i = await V.submitJob(e, {});
          await i.waitForJobCompletion();
          const s = await i.fetchResultData("Output_JSON");
          this._reportTemplatesInfo = s?.value ?? [];
        }
        this._reportTemplatesInfo = this._reportTemplatesInfo.filter((i) => {
          const s = i.reportOptions;
          if (s?.reportSectionOverrides) {
            let a = 0;
            return Object.keys(s.reportSectionOverrides).forEach((o) => {
              s.reportSectionOverrides[o].hasOwnProperty("sourceId") && a++;
            }), a <= 1;
          } else
            return !0;
        });
      } catch (i) {
        console.error("Failed to fetch report templates:", i);
      }
  }
  _getExportOptions() {
    const e = this._exportType === "PDF" ? "display-block" : "display-none", t = this._addTitle ? "display-block" : "display-none", i = this._addMap ? "display-flex" : "display-none", s = this._titleValue ? this._titleValue : this.defaultExportTitle ? this.defaultExportTitle : "", a = this._addResults ? "" : "display-none";
    return l`<div class=${x(e)}><p class="instructional-text">${this._translations.selectContentTip}</p><div class="padding-top-sides-1 padding-inline-start-0"><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=${`indent-group margin-top-1 ${a}`}><div class="margin-bottom-0-5"><calcite-label class="label-margin-0">${this._translations.selectPDFLabelOption}</calcite-label></div><div><pdf-download .defaultNumLabelsPerPage=${Number.parseInt(this.defaultNumLabelsPerPage.toString(), 10)} .disabled=${!this._downloadActive} ${_(this._downloadTools)}></pdf-download></div></div><div class="padding-top-sides-1 padding-inline-start-0"><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=${`${t} indent-group margin-top-0-5`}><calcite-input-text class="padding-inline-start-0 padding-top-1-2" @calciteInputTextInput=${() => this._changeTitle()} .placeholder=${this._translations.titlePlaceholder} .value=${s} ${_(this._titleElement)}></calcite-input-text></div><div class="padding-top-sides-1 padding-inline-start-0"><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 padding-inline-start-0 ${i}`}><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(e) {
    let t;
    const i = this._pnStateContextProvider.value;
    return Object.keys(i.managedLayers).some((s) => {
      const a = this.mapView?.map.layers.findIndex((o) => o.title === s);
      return i.managedLayers[s] === e && a !== void 0 ? (t = this.mapView?.map.layers.getItemAt(a), !0) : !1;
    }), t;
  }
  _updateExportGraphics(e = !1) {
    (e || !this._exportGraphics || !this._addMap) && this._removeExportGraphics(), this._exportGraphics && this._addMap && this._addExportGraphics();
  }
  _removeExportGraphics() {
    const e = this._getManagedLayer("sketch"), t = this._getManagedLayer("buffer");
    e && e.graphics.removeAll(), t && t.graphics.removeAll();
  }
  _addExportGraphics() {
    const e = this._getManagedLayer("sketch"), t = this._getManagedLayer("buffer");
    this._refineGraphics.forEach((i) => {
      e?.add(i.drawnGraphic), t?.add(i.bufferGraphic);
    }), this._selectionSets.forEach((i) => {
      if (i.download && (e && i.sketchGraphic && e.graphics.add(i.sketchGraphic), t)) {
        const s = {
          type: "simple-fill",
          color: this.bufferColor,
          outline: {
            color: this.bufferOutlineColor,
            width: 1
          }
        }, a = new ie({
          geometry: i.buffer,
          symbol: s
        });
        a && t.graphics.add(a);
      }
    });
  }
  async _getExportCropArea() {
    if (!this.mapView)
      return;
    const [e, t] = this.mapView.size || [0, 0];
    if (e <= 0 || t <= 0)
      return;
    const i = [], s = (c) => {
      c && isFinite(c.xmin) && isFinite(c.ymin) && isFinite(c.xmax) && isFinite(c.ymax) && i.push({
        xmin: c.xmin,
        ymin: c.ymin,
        xmax: c.xmax,
        ymax: c.ymax,
        sr: c.spatialReference
      });
    }, a = (c) => {
      c?.graphics.forEach((r) => {
        const m = r?.geometry;
        m && (m.extent ? s(m.extent) : typeof m.x == "number" && typeof m.y == "number" && i.push({
          xmin: m.x,
          ymin: m.y,
          xmax: m.x,
          ymax: m.y,
          sr: m.spatialReference
        }));
      });
    };
    a(this._getManagedLayer("buffer")), a(this._getManagedLayer("sketch"));
    const o = [];
    if (this._selectionSets.forEach((c) => {
      const r = (m, T) => {
        m && T?.length && o.push(m.queryExtent({ objectIds: T }).then((A) => A?.extent ?? null).catch(() => null));
      };
      c.workflowType === "REFINE" && c.refineInfos ? Object.keys(c.refineInfos).forEach((m) => {
        const T = c.refineInfos[m];
        r(T?.layerView, T?.addIds || []);
      }) : r(c.layerView, c.selectedIds || []);
    }), o.length > 0 && (await Promise.all(o)).forEach((r) => s(r)), i.length === 0)
      return;
    const n = i[0].sr;
    let h = i[0].xmin, p = i[0].ymin, g = i[0].xmax, d = i[0].ymax;
    for (let c = 1; c < i.length; ++c) {
      const r = i[c];
      r.xmin < h && (h = r.xmin), r.ymin < p && (p = r.ymin), r.xmax > g && (g = r.xmax), r.ymax > d && (d = r.ymax);
    }
    const $ = [
      { x: h, y: p, spatialReference: n },
      { x: h, y: d, spatialReference: n },
      { x: g, y: p, spatialReference: n },
      { x: g, y: d, spatialReference: n }
    ];
    let f = Number.POSITIVE_INFINITY, y = Number.POSITIVE_INFINITY, b = Number.NEGATIVE_INFINITY, S = Number.NEGATIVE_INFINITY;
    for (const c of $) {
      const r = this.mapView.toScreen(c);
      !r || !isFinite(r.x) || !isFinite(r.y) || (r.x < f && (f = r.x), r.y < y && (y = r.y), r.x > b && (b = r.x), r.y > S && (S = r.y));
    }
    if (!isFinite(f) || !isFinite(y) || !isFinite(b) || !isFinite(S))
      return;
    const E = 24;
    f = Math.max(0, Math.floor(f - E)), y = Math.max(0, Math.floor(y - E)), b = Math.min(e, Math.ceil(b + E)), S = Math.min(t, Math.ceil(S + E));
    const O = b - f, R = S - y;
    if (O <= 0 || R <= 0)
      return;
    const D = 8 / 10.5, F = (f + b) / 2, M = (y + S) / 2;
    let u = Math.max(O, R * D), w = u / D;
    const L = Math.min(e / u, t / w);
    L > 1 && (u *= L, w *= L), u > e && (u = e), w > t && (w = t);
    let I = F - u / 2, C = M - w / 2;
    return I = Math.max(0, Math.min(I, e - u)), C = Math.max(0, Math.min(C, t - w)), {
      x: Math.floor(I),
      y: Math.floor(C),
      width: Math.floor(u),
      height: Math.floor(w)
    };
  }
  _getRefinePage() {
    const e = this._hasSelections();
    return l`<calcite-panel>${this._getLabel(this._translations.refineSelection, !1, "header-label")}${e ? l`<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} ${_(this._refineSelection)}></refine-selection></div>` : this._getNotice(this._translations.refineTipNoSelections, "padding-sides-1")}</calcite-panel>`;
  }
  _getPageNavButtons(e, t, i, s, a, o) {
    return l`<div class="padding-bottom-1"><div class="display-flex padding-top-sides-1"><calcite-button .disabled=${t} @click=${i} width=full><span class="font-weight-500">${e}</span></calcite-button></div><div class="display-flex padding-top-1-2 padding-sides-1"><calcite-button appearance=outline .disabled=${a} @click=${o} width=full><span class="font-weight-500">${s}</span></calcite-button></div></div>`;
  }
  _changeTitle() {
    this._titleElement.value?.value && (this._titleValue = this._titleElement.value.value || "");
  }
  _getNotice(e, t = "padding-1", i = "") {
    return l`<calcite-notice class=${x(t)} icon=lightbulb kind=success open><div class=${x(i)} slot=message>${e}</div></calcite-notice>`;
  }
  _getLabel(e, t = !1, i = "font-bold", s = "padding-top-sides-1") {
    return i += t ? " label-margin-0" : "", l`<div class=${x(s)}><calcite-label class=${x(i)}>${e}</calcite-label></div>`;
  }
  _getExportSelectionLists() {
    return this._selectionSets.reduce((e, t) => {
      const i = this._getSelectionSetIds(t), s = t.workflowType !== "REFINE" || i.length > 0;
      return !this._downloadActive && t.download && s && (this._downloadActive = !0), s && e.push(l`<div class="display-flex padding-sides-1 padding-bottom-1"><calcite-checkbox .checked=${t.download} class="align-center" @calciteCheckboxChange=${() => {
        this._toggleDownload(t.id);
      }}></calcite-checkbox><calcite-list class="list-border margin-start-1-2 width-full" id=download-list label><calcite-list-item .disabled=${!t.download} .label=${t.label} @click=${() => {
        this._toggleDownload(t.id);
      }}><div slot=content><div class="list-label">${t.label}</div><div class="list-description">${t.layerView?.layer.title}</div><div class="list-description">${this._translations.selectedFeatures.replace("{{n}}", i.length.toString())}</div></div></calcite-list-item></calcite-list></div>`), e;
    }, []) || l`<div></div>`;
  }
  async _toggleDownload(e) {
    let t = !1;
    this._selectionSets = this._selectionSets.map((i) => {
      let s = !1;
      return i.refineInfos && Object.keys(i.refineInfos).forEach((a) => {
        i.refineInfos[a].addIds.length && (s = !0);
      }), (i.workflowType !== "REFINE" || s) && (i.download = i.id === e ? !i.download : i.download, t = i.download ? !0 : t), i;
    }), this._updateExportGraphics(!0), this._downloadActive = t, this._fetchingData = !0, this._numDuplicates = await this._getNumDuplicates(), this._fetchingData = !1, await this._highlightFeatures();
  }
  async _standardExport() {
    const e = this._addResults ? this._getSelectionIdsAndViews(this._selectionSets, !0) : {};
    if (this._exportType === "PDF") {
      let t = "";
      if (this._addMap && this.mapView) {
        const i = await this._getExportCropArea(), [s, a] = this.mapView.size || [0, 0], o = 2e3, n = i?.width ?? s, h = i?.height ?? a;
        let p = 1500, g = 2e3;
        if (n > 0 && h > 0) {
          const f = o / Math.max(n, h);
          p = Math.max(1, Math.round(n * f)), g = Math.max(1, Math.round(h * f));
        }
        const d = { width: p, height: g };
        i && (d.area = i), t = (await this.mapView.takeScreenshot(d))?.dataUrl;
      }
      this._fetchingData = !0, this._downloadTools.value && this._removeDuplicates.value && this.mapView?.map && await this._downloadTools.value.downloadPDF(this.mapView.map, e, this._removeDuplicates.value.checked, this._addTitle && this._titleElement.value ? this._titleElement.value.value : "", t), this._fetchingData = !1;
    }
    this._exportType === "CSV" && (this._fetchingData = !0, this._downloadTools.value && this.mapView?.map && await this._downloadTools.value.downloadCSV(this.mapView.map, e, this._removeDuplicates.value?.checked || !1), this._fetchingData = !1);
  }
  _getSelectionIdsAndViews(e, t = !1) {
    return (t ? e.filter((s) => s.download) : e).reduce((s, a) => {
      if (a.workflowType === "REFINE")
        Object.keys(a.refineInfos).forEach((o) => {
          const n = a.refineInfos[o];
          if (n.addIds) {
            const h = n.layerView.layer.id;
            s = this._updateExportInfos(s, h, a.label, n.addIds, n.layerView);
          }
        });
      else {
        const o = a?.layerView?.layer.id;
        o !== void 0 && a.layerView && (s = this._updateExportInfos(s, o, a.label, a.selectedIds, a.layerView));
      }
      return s;
    }, {});
  }
  _updateExportInfos(e, t, i, s, a) {
    return t && Object.keys(e).indexOf(t) > -1 ? (e[t].ids = [.../* @__PURE__ */ new Set([...e[t].ids, ...s])], e[t].selectionSetNames.push(i)) : t && (e[t] = {
      ids: s,
      layerView: a,
      selectionSetNames: [i]
    }), e;
  }
  _getAction(e, t, i, s, a = !1, o = "") {
    return l`<calcite-action .disabled=${!e} .icon=${t} icon-flip-rtl .indicator=${a} @click=${s} slot=${o ?? k} .text=${i}></calcite-action>`;
  }
  _updateForSelection(e) {
    this._numSelected = e.detail, this._saveEnabled = this._numSelected > 0;
  }
  async _home() {
    await this._clearSelection(), this._setPageType("LIST");
  }
  async _saveSelection() {
    const e = await this._selectTools.value?.getSelection();
    if (e) {
      const t = this._selectTools.value?.isUpdate;
      this._selectionSets = t ? this._selectionSets.map((i) => i.id === e.id ? e : i) : [...this._selectionSets, e];
    }
    return this._home();
  }
  async _clearSelection() {
    await this._selectTools.value?.clearSelection(), this._numSelected = 0, this._activeSelection = void 0;
  }
  async _deleteSelection(e, t) {
    return t.stopPropagation(), this._selectionSets = this._selectionSets.filter((i, s) => (i.workflowType === "REFINE" && (this._refineGraphics = []), s !== e ? i : !1)), this._highlightFeatures();
  }
  _gotoSelection(e, t) {
    e.selectedIds && e.layerView && H(e.selectedIds, e.layerView, t, this.featureHighlightEnabled, this.featureEffect);
  }
  _openSelection(e, t) {
    t.stopPropagation(), this._activeSelection = e, this._pageType = e.workflowType === "REFINE" ? "REFINE" : "SELECT";
  }
  async _highlightFeatures() {
    const e = this._pnStateContextProvider.value;
    this._clearHighlight();
    const t = this._getSelectionIdsAndViews(this._selectionSets, this._pageType === "EXPORT"), i = Object.keys(t);
    if (i.length > 0)
      for (let s = 0; s < i.length; s++) {
        const a = t[i[s]];
        if (a.layerView && this.mapView) {
          const o = await j(a.ids, a.layerView, this.mapView);
          e.highlightHandles.push(o);
        }
      }
  }
  _checkPopups() {
    typeof this._popupsEnabled != "boolean" && (this._popupsEnabled = !!this.mapView?.popupEnabled);
  }
  _clearHighlight() {
    const e = this._pnStateContextProvider.value;
    e && e.highlightHandles && e.removeHandles();
  }
}
U("public-notification", ce);
export {
  ce as PublicNotification
};
