/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { c as I } from "../../chunks/runtime.js";
import { a as x, g as w } from "../../chunks/mapViewUtils.js";
import { u as A } from "../../chunks/useT9n.js";
import { css as M, html as n, nothing as y } from "lit";
import { createRef as p, ref as u } from "lit-html/directives/ref.js";
import { LitElement as E, createEvent as c, noShadowRoot as L, safeClassMap as v } from "@arcgis/lumina";
import { p as k } from "../../chunks/queryUtils.js";
import P from "@arcgis/core/form/ExpressionInfo.js";
import S from "@arcgis/core/layers/FeatureLayer.js";
import C from "@arcgis/core/form/elements/FieldElement.js";
import $ from "@arcgis/core/form/FormTemplate.js";
import F from "@arcgis/core/views/MapView.js";
import V from "@arcgis/core/Graphic.js";
import * as f from "@arcgis/core/core/reactiveUtils.js";
import * as T from "@arcgis/core/rest/locator.js";
import b from "@arcgis/core/request.js";
import * as R from "exifr";
import U from "@arcgis/core/geometry/Point.js";
import z from "@arcgis/core/geometry/SpatialReference.js";
const H = M`@layer{:host{display:block}.hide-editor-toolbar .esri-editor__panel-toolbar{display:none!important}.esri-editor__panel-content{padding-block:0px!important}.esri-editor .esri-item-list__group__header,.esri-editor__panel-content__section .esri-widget__heading{display:none!important}.esri-editor .esri-item-list__filter-container--sticky{padding-block:0px!important;padding-inline:10px!important}.search-widget{width:92%!important;margin:5px 14px 20px}.display-none{display:none!important}.hide-map{height:1%!important;visibility:hidden;position:static!important}.show-map{padding:10px!important;position:absolute!important;bottom:0;height:auto!important;width:calc(100% - 22px)}.notice-msg{padding:10px;width:calc(100% - 20px)}.edit-location-btn{margin:5px;display:flex}.esri-editor__panel-content{padding-block:10px!important}.image-preview-container{padding:10px}.esri-editor{height:auto!important}.height-fit-content{height:fit-content!important}.content-container{padding:1.5rem}.instruction-text{margin-bottom:1.5rem;font-size:1rem}.selected-card{border:2px solid var(--calcite-ui-brand)}.upload-img-footer-container{width:100%;gap:5px;display:grid}.info-container{display:flex;align-items:center;gap:6px;margin-bottom:10px}.info-container calcite-icon{--calcite-icon-color: var(--calcite-color-brand)}.info-container span{font-size:12px;color:var(--calcite-ui-text-3)}.padding-10{padding:10px}.report-selection-container{display:flex;flex-direction:column;padding:10px;--calcite-card-border-color: var(--calcite-color-border-1)}.pb-12{padding-bottom:12px!important}.pt-0{padding-top:0!important}.pt-15{padding-top:15px!important}.option-description-container{display:flex;align-items:center;gap:6px}.cursor-pointer{cursor:pointer;padding:6px 0}.card-body-content{display:flex;flex-direction:row;align-items:center;padding:10px 5px;gap:15px}.text-stack{display:flex;flex-direction:column;gap:2px}.option-title{font-weight:var(--calcite-font-weight-bold);color:var(--calcite-ui-text-1);font-size:var(--calcite-font-size--1)}.option-description{color:var(--calcite-ui-text-3);font-size:var(--calcite-font-size--1)}.action-footer{display:flex;justify-content:center;margin-top:16px}.analysis-wrapper{display:flex;flex-direction:column;align-items:center;gap:5px;text-align:center;margin:auto}.analyzing-icon{--calcite-icon-color: var(--calcite-color-brand);animation:sparkle 2s infinite ease-in-out}.adjusted-height{height:30px!important;min-height:auto!important}@keyframes sparkle{0%,to{transform:scale(1)}50%{transform:scale(1.5)}}@media only screen and (max-width:600px){.esri-editor__panel-content{padding-block:0!important;min-height:0!important}}}`, _ = "geocodedLocation", D = `Extract the address from the user's message and return it in JSON format '{"address":"<address>"}'. If no address is found, return null.`;
class N extends E {
  constructor() {
    super(...arguments), this.customizeSubmit = !1, this.enableSearch = !1, this.enableSnapping = !1, this.floorLevel = "", this.isMobile = !1, this.selectedLayerId = "", this.showGuidingMsg = !0, this.submitNewReportsMessage = "", this.updateMapPosition = !1, this.reportingArea = !1, this.reportingAreaLayer = "", this.reportingAreaMessage = "", this.showSketchWidgets = !1, this.allowMultipleCreation = !1, this.popupEnabled = !1, this.showLayerVisibilityMsg = !1, this.enablePhotoLocation = !1, this.enableMessageLocation = !1, this._currentPage = "templatePicker", this._showSearchComponent = this.enableSearch, this._layerInfos = [], this._inValidGeometryDrawn = !1, this._selectedImageBase64 = "", this._enteredMessage = "", this._analysisFailed = !1, this._translations = A({ name: "create-feature", blocking: !0 }), this._addingAttachment = !1, this._uploadedImage = null, this._calciteNotice = p(), this._editor = p(), this._mapViewContainer = p(), this._searchRef = p(), this._inputImageForAI = p(), this._guidingMessageRefNode = p(), this._abortController = new AbortController(), this._awaitingLayerEdits = !1, this._pendingAttachmentUpload = !1, this.success = c(), this.fail = c(), this.drawComplete = c(), this.editingLocation = c(), this.editingAttachment = c(), this.progressStatus = c(), this.modeChanged = c(), this.activeFeatureCountChange = c(), this.createFeatureEditorInitialized = c(), this.createFeatureEditorClosed = c(), this._onLayerEdits = async (e) => {
      if (!this._awaitingLayerEdits)
        return;
      const t = [
        ...e.addedFeatures || []
      ].filter((i) => i?.error);
      if (t.length) {
        this._onFail(t[0].error);
        return;
      }
      if (this._pendingAttachmentUpload) {
        const i = e?.addedFeatures?.[0]?.objectId;
        if (i && this._uploadedImage && this._selectedLayer)
          try {
            const a = new FormData();
            a.set("keywords", "ai-image"), a.set("attachment", this._uploadedImage), a.append("f", "json");
            const s = new V({
              attributes: {
                [this._selectedLayer.objectIdField]: i
              }
            });
            await this._selectedLayer.addAttachment(s, a);
          } catch (a) {
            this._onFail(a);
            return;
          }
      }
      this._awaitingLayerEdits = !1, this._pendingAttachmentUpload = !1, this.success.emit();
    };
  }
  static {
    this.properties = { appName: 1, customizeSubmit: 5, enableSearch: 5, enableSnapping: 5, floorLevel: 1, formElements: 1, isMobile: 5, mapView: 0, searchConfiguration: 0, selectedLayerId: 1, showGuidingMsg: 5, submitNewReportsMessage: 1, updateMapPosition: 5, reportingArea: 5, reportingAreaLayer: 1, reportingAreaMessage: 1, showSketchWidgets: 5, allowMultipleCreation: 5, popupEnabled: 5, showLayerVisibilityMsg: 5, enablePhotoLocation: 5, enableMessageLocation: 5, aiImageExtraction: 0, aiTextExtraction: 0, _currentPage: 16, _showSearchComponent: 16, _layerInfos: 16, _inValidGeometryDrawn: 16, _selectedImageBase64: 16, _enteredMessage: 16, _analysisFailed: 16, _updatedMapView: 16, _translations: 16 };
  }
  static {
    this.styles = H;
  }
  static {
    this.shadowRootOptions = L;
  }
  willUpdate(e) {
    e.has("mapView") && this.hasUpdated && this.mapViewWatchHandler(), e.has("isMobile") && this.hasUpdated && this.isMobileHandler(), e.has("enableSearch") && this.hasUpdated && this.searchHandler(), e.has("searchConfiguration") && this.hasUpdated && this.searchConfigurationHandler(this.searchConfiguration, e.get("searchConfiguration"));
  }
  async mapViewWatchHandler() {
    this.mapView && await this.mapView.when(async () => {
      this._aiAnalysisInfo && !this._aiAnalysisInfo.canUseAI && await this.init();
    });
  }
  async isMobileHandler() {
    this.modeChanged.emit();
  }
  searchHandler() {
    this._showSearchComponent = this.enableSearch, this.isMobile && this._adjustPanelContentHeight();
  }
  async searchConfigurationHandler(e, t) {
    !this._searchRef.value || !e || !t || (e.allPlaceholder !== t.allPlaceholder ? this._searchRef.value.allPlaceholder = e.allPlaceholder || "" : !this._searchRef.value.searchAllDisabled !== e.searchAllEnabled ? this._searchRef.value.searchAllDisabled = !e.searchAllEnabled : this._updatedMapView && JSON.stringify(e.sources) !== JSON.stringify(t.sources) && (this._searchRef.value.sources = this._getSearchConfig(e, this._updatedMapView)?.sources || []), this._updateSearchActiveSourceIndex());
  }
  async submit() {
    const e = this._editor.value?.activeWorkflow;
    if (e && (this._pendingAttachmentUpload = !!(this._selectedLayer && this._selectedLayer.capabilities.data.supportsAttachment && this._selectedImageBase64), this._awaitingLayerEdits = !0, e.data?.creationInfo && this._updatedMapView && (e.data.creationInfo.view = this._updatedMapView), await e.save(), e.data.viewModel.failures.length)) {
      const t = e.data.viewModel.failures[0].error;
      this._currentPage = "drawing", this._onFail(t);
      return;
    }
  }
  async refresh(e) {
    this._editor.value && (e ? await this._setFloorLevel(e) : this.reportingArea && this.reportingAreaLayer && this._currentPage !== "drawing" ? await this.queryIntersectingFeatures() : this._currentPage !== "drawing" && (this._inValidGeometryDrawn = !1, this.drawComplete.emit(this._inValidGeometryDrawn)));
  }
  async showForm() {
    this.progressStatus.emit(100), this._editor.value?.classList.remove("display-none"), this._mapViewContainer.value?.classList.replace("show-map", "hide-map"), this._currentPage = "featureForm";
  }
  async load() {
    this._showSearchComponent = this.enableSearch, this._aiAnalysisInfo = await this._getAIAnalysisInfo(), this._currentPage = this._aiAnalysisInfo.canUseAI ? "chooseReportType" : "templatePicker";
  }
  async loaded() {
    this._aiAnalysisInfo && !this._aiAnalysisInfo.canUseAI && await this.init();
  }
  async updated() {
    if (this.isMobile && this.updateMapPosition) {
      const e = this._currentPage === "drawing" ? 80 : 30;
      await this._searchRef.value?.componentOnReady();
      const t = this._showSearchComponent ? this._searchRef.value?.offsetHeight : 0;
      await this._calciteNotice.value?.componentOnReady();
      const a = (this._calciteNotice.value?.offsetHeight || 0) + t + e;
      this._mapViewContainer.value && (this._mapViewContainer.value.style.top = `${a}px`);
    }
    this.reportingAreaMessage && this._guidingMessageRefNode.value?.children[0] && (this._guidingMessageRefNode.value.children[0].style.margin = "0px");
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this._editor.value && (this._editor.value.destroy(), this.enableSnapping && this.mapView?.ui.view && (this.mapView.ui.view.grid = null), this._removeHandlers(), this.createFeatureEditorClosed.emit());
  }
  render() {
    const e = this._currentPage === "loading" ? "" : "display-none", t = this.isMobile && this.updateMapPosition ? "show-map" : "display-none", i = this._inValidGeometryDrawn ? "danger" : "success", a = this._inValidGeometryDrawn ? "exclamation-mark-triangle" : "lightbulb", s = this.showLayerVisibilityMsg && this._currentPage === "templatePicker", r = (this.showGuidingMsg || s) && this._currentPage !== "loading" && this._currentPage !== "drawingMultipleFeatures";
    let o = this._translations.chooseCategoryMsg;
    const l = this._aiAnalysisInfo?.results?.filter((h) => !h.success && h.key !== _), d = l?.length ? !0 : this._analysisFailed, m = this._getAnalysisErrorMessage(l?.length), g = this._aiAnalysisInfo?.canUseAI && ["chooseReportType", "analyzingImage", "analyzingMessage", "imageUpload", "messageInput"].includes(this._currentPage);
    return this._inValidGeometryDrawn ? o = this.reportingAreaMessage || this._translations.reportOutsideAreaMessage : this._currentPage === "drawing" || this._currentPage === "editing" ? o = this._translations.provideLocationMsg : this._currentPage === "featureForm" ? o = this._aiAnalysisInfo?.results?.filter((h) => h.success).length ? this._analysisMode === "text" ? this._translations.textReviewMsg : this._translations.formReviewMsg : this._translations.provideDetailsMsg : s && (o = this._translations.enableFeatureTemplatesMessage), n`${d && n`<calcite-alert auto-close icon=x-octagon kind=danger label @calciteAlertClose=${() => {
      this._analysisFailed = !1;
    }} open placement=top><div slot=title>${this._translations.error}</div><div slot=message>${m}</div></calcite-alert>` || ""}${g && n`<calcite-panel>${this._currentPage === "chooseReportType" && this._getReportTypePage() || ""}${this._currentPage === "imageUpload" && this._aiImageExtractionPage() || ""}${this._currentPage === "messageInput" && this._aiTextExtractionPage() || ""}${this._currentPage === "analyzingImage" && this._getAnalyzingImagePage() || ""}${this._currentPage === "analyzingMessage" && this._getAnalyzingMessagePage() || ""}</calcite-panel>` || ""}${!g && n`${r && n`<calcite-notice class="notice-msg" .icon=${a} .kind=${i} open ${u(this._calciteNotice)}><div slot=message .innerHTML=${o ?? ""} ${u(this._guidingMessageRefNode)}></div></calcite-notice>` || ""}${this._selectedImageBase64 && this._currentPage === "featureForm" && n`<div class="image-preview-container"><calcite-label>${this._translations.photo}</calcite-label><img class="width-full" src=${this._selectedImageBase64 ?? y}></div>` || ""}<calcite-loader class=${v(e)} label scale=s></calcite-loader>${this._currentPage === "featureForm" && this.isMobile && n`<calcite-button appearance=transparent class="edit-location-btn" icon-start=pin @click=${this.editLocation}>${this._translations.editLocationLabel}</calcite-button>` || ""}${this._showSearchComponent && this._updatedMapView && this._selectedLayer && this._getSearchComponent() || ""}${this._updatedMapView && this._selectedLayer && this._getEditor() || ""}` || ""}<div class=${v(t)} ${u(this._mapViewContainer)}></div>`;
  }
  async init() {
    this.mapView && this.selectedLayerId && (this._updatedMapView = this.mapView, await (this.isMobile && this.updateMapPosition ? this.createMobileMapView() : this._loadLayerInfos()));
  }
  async createMobileMapView() {
    this._mapViewContainer.value && this.mapView && (this._mapViewContainer.value.classList.add("hide-map"), await new F({
      map: this.mapView.map,
      container: this._mapViewContainer.value,
      zoom: this.mapView.zoom,
      center: this.mapView.center,
      popupEnabled: this.popupEnabled
    }).when((e) => {
      this._updatedMapView = e;
      const t = document.createElement("arcgis-home");
      t.view = this._updatedMapView, this._updatedMapView.ui.add(t, "top-left"), this._loadLayerInfos();
    }, (e) => {
      console.log(e);
    }));
  }
  async _loadLayerInfos() {
    const e = [], t = this._updatedMapView && await x(this._updatedMapView), i = this.mapView && await w(this.mapView, this.selectedLayerId);
    i && (this._selectedLayer = i, this._attachEditsListener(this._selectedLayer), !this._selectedLayer.isTable && t && t.forEach((a) => {
      e.push({
        layer: a,
        enabled: a.type === "feature" && a.id === this.selectedLayerId,
        addEnabled: !0,
        updateEnabled: !1,
        deleteEnabled: !1
      });
    })), this._layerInfos = e;
  }
  _attachEditsListener(e) {
    this._attachedEditsLayerId === e.id && this._layerEditsHandler || (this._layerEditsHandler?.remove(), this._attachedEditsLayerId = e.id, this._layerEditsHandler = e.on("edits", this._onLayerEdits));
  }
  _onFail(e) {
    this._awaitingLayerEdits = !1, this._pendingAttachmentUpload = !1, this.fail.emit(e);
  }
  _getReportTypePage() {
    const e = this._hasImageExtraction(), t = this._hasTextExtraction();
    return n`<div class="report-selection-container"><calcite-label class="pb-12">${this._translations.createReportHeading}</calcite-label><div class="option-description-container"><span class="option-description">${this._translations.aiAssistedReport}</span><calcite-icon icon=effects scale=s></calcite-icon></div>${t && n`<calcite-card class="cursor-pointer pt-0" @click=${() => {
      this._analysisMode = "text", this.progressStatus.emit(35), this._currentPage = "messageInput";
    }} @keydown=${(i) => {
      this._activateCardFromKeyboard(i, () => {
        this._analysisMode = "text", this.progressStatus.emit(35), this._currentPage = "messageInput";
      });
    }}><div slot=description class="card-body-content"><calcite-icon icon=speech-bubble scale=m></calcite-icon><div class="text-stack"><span class="option-title">${this._translations.useDescription}</span><span class="option-description">${this._translations.aiTextAssistantDescription}</span></div></div></calcite-card>` || ""}${e && n`<calcite-card class="cursor-pointer" @click=${() => {
      this._analysisMode = "image", this.progressStatus.emit(35), this._currentPage = "imageUpload";
    }} @keydown=${(i) => {
      this._activateCardFromKeyboard(i, () => {
        this._analysisMode = "image", this.progressStatus.emit(35), this._currentPage = "imageUpload";
      });
    }}><div slot=description class="card-body-content"><calcite-icon aria-hidden=true icon=camera scale=m style="color: var(--calcite-ui-text-2)"></calcite-icon><div class="text-stack"><span class="option-title">${this._translations.usePhoto}</span><span class="option-description">${this._translations.aiAssistantDescription}</span></div></div></calcite-card>` || ""}<span class="option-description pt-15">${this._translations.manualReport}</span><calcite-card class="cursor-pointer pt-0" @click=${() => {
      this._currentPage = "templatePicker", this.init();
    }} @keydown=${(i) => {
      this._activateCardFromKeyboard(i, () => {
        this._currentPage = "templatePicker", this.init();
      });
    }}><div slot=description class="card-body-content"><calcite-icon aria-hidden=true icon=pencil scale=m></calcite-icon><div class="text-stack"><span class="option-title">${this._translations.fillOutManually}</span><span class="option-description">${this._translations.startBlank}</span></div></div></calcite-card></div>`;
  }
  _activateCardFromKeyboard(e, t) {
    (e.key === "Enter" || e.key === " ") && (e.preventDefault(), t());
  }
  _getEditor() {
    return n`<arcgis-editor class=height-fit-content .view=${this._updatedMapView} .layerInfos=${this._layerInfos} hide-edit-features-section .hideSettingsMenu=${!this.enableSnapping} .hideSketch=${!this.showSketchWidgets || this._selectedLayer?.geometryType === "point"} .hideSnappingControlsElementsEnabledToggle=${!this.enableSnapping} @arcgisReady=${this._onEditorComponentReady} @arcgisPropertyChange=${this._onEditorPropertyChange} @arcgisSketchUpdate=${this._onSketchUpdate} ${u(this._editor)}></arcgis-editor>`;
  }
  _getSearchComponent() {
    const e = this._currentPage === "drawing" || this._currentPage === "editing" ? "" : "display-none", t = this.searchConfiguration && this._updatedMapView ? this._getSearchConfig(this.searchConfiguration, this._updatedMapView) : void 0;
    return this._updateSearchActiveSourceIndex(), n`<arcgis-search class=${`search-widget ${e}`} .view=${this._updatedMapView} @arcgisSearchComplete=${this.searchComplete} popup-disabled result-graphic-disabled .includeDefaultSourcesDisabled=${!!t?.sources?.length} .sources=${t?.sources || []} .allPlaceholder=${t?.allPlaceholder} .searchAllDisabled=${!t?.searchAllEnabled} ${u(this._searchRef)}></arcgis-search>`;
  }
  _aiImageExtractionPage() {
    const e = this._selectedImageBase64 !== "", t = e ? this._translations.replaceImage : this._translations.imageUploadLimitHint;
    return n`<calcite-notice class="notice-msg" icon=effects kind=brand open><div slot=message>${this._translations.aiAssistantProcessingHint}</div></calcite-notice><div class="padding-10"><calcite-label><div>${this._translations.photo}<span style="color: var(--calcite-color-status-danger)">*</span></div><calcite-input type=file accept="image/*;capture=camera" @calciteInputInput=${this._onImageUpload} ${u(this._inputImageForAI)}></calcite-input></calcite-label><div class="info-container"><calcite-icon aria-hidden=true icon=information scale=s></calcite-icon><span>${t}</span></div>${e && n`<img alt=${this._translations.photo ?? y} class="width-full" src=${this._selectedImageBase64 ?? y}>` || ""}</div><div slot=footer class="upload-img-footer-container"><calcite-button width=full .disabled=${!e} id=next-btn @click=${this._analyzeImage}>${this._translations.next}</calcite-button><calcite-button width=full appearance=outline kind=brand @click=${() => this.modeChanged.emit()}>${this._translations.cancel}</calcite-button></div>`;
  }
  _aiTextExtractionPage() {
    const e = this._enteredMessage.trim();
    return n`<calcite-notice class="notice-msg" icon=effects kind=brand open><div slot=message>${this._translations.aiTextProcessingHint}</div></calcite-notice><div class="padding-10"><calcite-label><div>${this._translations.description}<span style="color: var(--calcite-color-status-danger)">*</span></div><calcite-text-area @input=${(t) => {
      this._enteredMessage = t.target.value;
    }} .placeholder=${this._translations.messageInputHint} resize=vertical rows=6 .value=${this._enteredMessage}></calcite-text-area></calcite-label><div class="info-container"><calcite-icon icon=information scale=s></calcite-icon><span>${this._translations.descriptionRequiredHint}</span></div></div><div slot=footer class="upload-img-footer-container"><calcite-button width=full .disabled=${!e} id=next-btn @click=${this._analyzeMessage}>${this._translations.next}</calcite-button><calcite-button width=full appearance=outline kind=brand @click=${() => this.modeChanged.emit()}>${this._translations.cancel}</calcite-button></div>`;
  }
  _getAnalyzingImagePage() {
    return n`<div class="analysis-wrapper"><calcite-label layout=inline><calcite-icon class="analyzing-icon" icon=effects scale=s></calcite-icon><span>${this._translations.analyzingImage}</span></calcite-label><calcite-button class="skip-btn" appearance=transparent @click=${() => {
      this._abortController.abort(), this._currentPage = "templatePicker";
    }}>${this._translations.skip}</calcite-button></div>`;
  }
  _getAnalyzingMessagePage() {
    return n`<div class="analysis-wrapper"><calcite-label layout=inline><calcite-icon class="analyzing-icon" icon=effects scale=s></calcite-icon><span>${this._translations.analyzingText}</span></calcite-label><calcite-button class="skip-btn" appearance=transparent @click=${() => {
      this._abortController.abort(), this._currentPage = "templatePicker";
    }}>${this._translations.skip}</calcite-button></div>`;
  }
  _onImageUpload(e) {
    const t = e.target;
    if (t) {
      const i = t.files[0], a = new FileReader();
      a.onload = (s) => {
        this._selectedImageBase64 = s.target?.result;
      }, i ? (a.readAsDataURL(i), this._uploadedImage = i) : (this._selectedImageBase64 = "", this._uploadedImage = null);
    }
  }
  async _analyzeImage() {
    this._abortController = new AbortController();
    const e = this._abortController.signal, t = await this._getAIAnalysisInfo();
    if (!t.canUseAI || !t.imageUrl || !this._inputImageForAI.value?.files?.length) {
      this._analysisFailed = !0, console.error(this._translations.error), this._resetAIAnalysisInfo(), await this.init();
      return;
    }
    try {
      this._analysisMode = "image", this._currentPage = "analyzingImage", this.progressStatus.emit(45);
      const i = this._inputImageForAI.value.files[0], a = await new Promise((r, o) => {
        const l = new FileReader();
        l.onloadend = () => r(l.result), l.onerror = o, this._inputImageForAI.value && l.readAsDataURL(i);
      });
      if (this.enablePhotoLocation) {
        const r = await R.gps(i);
        if (r?.longitude && r.latitude && this.mapView?.spatialReference) {
          const o = new U({
            longitude: r.longitude,
            latitude: r.latitude,
            spatialReference: new z({ wkid: 4326 })
          }), l = await k(o, this.mapView.spatialReference);
          this._aiAnalysisInfo && (this._aiAnalysisInfo.location = l);
        }
      }
      const s = this._getImageExtractionData();
      if (s.length) {
        const r = {
          input: a,
          data: s
        }, o = await b(t.imageUrl, {
          method: "post",
          headers: {
            "Content-Type": "application/json",
            "x-esri-authorization": `Bearer ${t.token}`,
            "x-esri-request-source": `instantapps/${this.appName}`
          },
          body: JSON.stringify(r),
          responseType: "json",
          signal: e
        });
        this._aiAnalysisInfo && (this._aiAnalysisInfo.results = o.data.results);
      }
      this._currentPage = "loading", await this.init();
    } catch (i) {
      i.name === "AbortError" ? console.error("Aborted", i) : (this._analysisFailed = !0, console.error("Analyzing failed", i)), this._resetAIAnalysisInfo(), this.init();
    }
  }
  async _analyzeMessage() {
    this._abortController = new AbortController();
    const e = this._abortController.signal, t = await this._getAIAnalysisInfo(), i = this._enteredMessage.trim(), a = this._getTextExtractionData();
    let s = { url: "", singleLineFieldName: "" };
    if (this.enableMessageLocation && (s = this._getLocatorConfig(), this._shouldExtractLocationFromText() && s.url && a.push({ key: _, context: D })), !t.canUseAI || !t.textUrl || !i || !a.length) {
      this._analysisFailed = !0, console.error(this._translations.error), this._resetAIAnalysisInfo(), await this.init();
      return;
    }
    try {
      this._analysisMode = "text", this._currentPage = "analyzingMessage", this.progressStatus.emit(45);
      const r = await b(t.textUrl, {
        method: "post",
        headers: {
          "Content-Type": "application/json",
          "x-esri-authorization": `Bearer ${t.token}`,
          "x-esri-request-source": `instantapps/${this.appName}`
        },
        body: JSON.stringify({
          input: i,
          data: a
        }),
        responseType: "json",
        signal: e
      });
      if (this._aiAnalysisInfo && (this._aiAnalysisInfo.results = r.data.results, s.url)) {
        const o = this._getExtractedAddress(r.data.results);
        o && (this._aiAnalysisInfo.location = await this._geocodeExtractedAddress(o, {
          url: s.url,
          singleLineFieldName: s.singleLineFieldName
        }));
      }
      this._currentPage = "loading", await this.init();
    } catch (r) {
      r.name === "AbortError" ? console.error("Aborted", r) : (this._analysisFailed = !0, console.error("Analyzing failed", r)), this._resetAIAnalysisInfo(), this.init();
    }
  }
  _resetAIAnalysisInfo() {
    const e = {
      imageUrl: "",
      textUrl: "",
      token: "",
      canUseAI: !1,
      location: void 0,
      results: []
    };
    this._selectedImageBase64 = "", this._enteredMessage = "", this._aiAnalysisInfo = e;
  }
  async _getAIAnalysisInfo() {
    const e = {
      imageUrl: "",
      textUrl: "",
      token: "",
      canUseAI: !1
    };
    if (this._hasImageExtraction() || this._hasTextExtraction()) {
      const i = (this.mapView?.map).portalItem.portal;
      if (i) {
        const a = await i.fetchSettings(), s = i?.helperServices.aiUtilityServices;
        s?.url && (s.api?.image_analyze && (e.imageUrl = s.url + s.api.image_analyze), s.api?.text_analyze ? e.textUrl = s.url + s.api.text_analyze : e.textUrl = `${s.url}/api/text/analyze`), i.credential && (e.token = i.credential.token), a?.aiAssistantsEnabled && !a.blockBetaApps && i?.user?.privileges?.includes("portal:user:useAIAssistants") && (e.canUseAI = !0);
      }
    }
    return e;
  }
  async queryIntersectingFeatures() {
    const e = this.mapView && await w(this.mapView, this.reportingAreaLayer);
    if (e) {
      const t = e.createQuery();
      t.geometry = this._drawnGeometry, t.spatialRelationship = "intersects";
      const a = await e.queryFeatureCount(t) === 0;
      this._inValidGeometryDrawn = a, this.drawComplete.emit(this._inValidGeometryDrawn);
    }
  }
  editLocation() {
    this.progressStatus.emit(75), this.editingLocation.emit(), this._editor.value?.classList.add("display-none"), this._mapViewContainer.value?.classList.replace("hide-map", "show-map"), this._currentPage = "editing";
  }
  async _onEditorComponentReady() {
    if (this._currentPage = "templatePicker", this._selectedLayer && this._selectedLayer.templates?.length === 1 && this._editor.value && this._updatedMapView) {
      const e = this._selectedLayer.templates[0], t = {
        layer: this._selectedLayer,
        template: e
      };
      await this._editor.value.startCreateFeaturesWorkflowAtFeatureCreation(t);
    }
    await this.hideEditorsElements(), this._editor.value && this.createFeatureEditorInitialized.emit(this._editor.value);
  }
  async _onEditorPropertyChange() {
    const e = this._editor.value;
    e?.state && (this._drawingHandler || (this._drawingHandler = f.watch(() => e.state, async (t) => {
      const i = this._editor.value?.activeWorkflow;
      t === "creating-features" && i?.formViewModel?.status === "not-loaded" && (this._mapViewContainer.value?.classList.replace("hide-map", "show-map"), this._selectedLayer && !this._selectedLayer.isTable && (this._currentPage = "drawing", this.progressStatus.emit(50), i?.sketchViewModel?.createGraphic && this._aiAnalysisInfo?.location && (await this._goToAndWaitForStationary({ center: this._aiAnalysisInfo.location }), this._selectedLayer.geometryType === "point" && await this._initializeSketchPoint(this._aiAnalysisInfo.location.clone()))), this.isMobile && this._adjustPanelContentHeight(), this._searchRef.value && await this._searchRef.value.setFocus()), t === "adding-attachment" || t === "editing-attachment" ? (this._addingAttachment = !0, this.editingAttachment.emit(!0)) : this._addingAttachment && (this.editingAttachment.emit(!1), this._addingAttachment = !1);
    })), this._featureFormHandler || (this._featureFormHandler = f.watch(() => e.activeWorkflow?.formViewModel?.status, (t) => {
      if (t === "loaded" && this._currentPage !== "editing")
        this._mapViewContainer.value?.classList?.replace("show-map", "hide-map"), setTimeout(() => {
          this._setFloorLevel(this.floorLevel), this._aiAnalysisInfo?.results && this._setAttributeValuesFromAIAnalysis();
        }, 500), !this.allowMultipleCreation && this._editor.value?.activeWorkflow && (this._editor.value.activeWorkflow.data.creationInfo.maxFeatures = 1), this._currentPage = "featureForm", this.progressStatus.emit(100), this.drawComplete.emit(!1);
      else if (t === "not-loaded" && this.allowMultipleCreation && this._currentPage !== "editing") {
        this._currentPage = "drawingMultipleFeatures";
        const i = this._updatedMapView, a = e.activeWorkflow;
        i && !i.activeTool && a?.sketchViewModel && this._selectedLayer?.geometryType && a.sketchViewModel.create(this._selectedLayer.geometryType);
      }
    })), this.allowMultipleCreation && e.activeWorkflow && (this._activeFeatureCountHandler || (this._activeFeatureCountHandler = f.watch(() => e.activeWorkflow?.data?.viewModel?.activeFeatureCount, (t) => {
      t === 0 && (this._currentPage = "drawing"), this.activeFeatureCountChange.emit(t);
    }))), await this.hideEditorsElements());
  }
  _adjustPanelContentHeight() {
    setTimeout(() => {
      const e = document.querySelector("arcgis-editor");
      e?.shadowRoot && e.shadowRoot.querySelectorAll(".esri-editor__panel-content").forEach((i) => {
        i.style.minHeight = "auto", i.style.height = this._showSearchComponent ? "30px" : "auto", i.style.padding = this._showSearchComponent ? "0px" : "18px 15px";
      });
    }, 500);
  }
  async _onSketchUpdate(e) {
    clearTimeout(this._sketchUpdateDebounceTimer), this._sketchUpdateDebounceTimer = window.setTimeout(async () => {
      const t = e?.detail?.detail?.graphics?.[0]?.geometry;
      t && (this._drawnGeometry = t, this.reportingArea && this.reportingAreaLayer && await this.queryIntersectingFeatures());
    }, 50);
  }
  async searchComplete(e) {
    if (!e?.detail?.results?.[0]?.results?.[0]?.feature)
      return;
    const t = e.detail.results[0].results[0].feature;
    let i;
    t && (await this._goToAndWaitForStationary(t.geometry), this._selectedLayer?.geometryType === "point" && t?.geometry && (i = t.geometry));
    const a = this._editor.value?.activeWorkflow;
    if (i && a?.sketchViewModel?.createGraphic)
      await this._initializeSketchPoint(i);
    else if (a?.sketchViewModel && a.sketchViewModel.updateGraphics.length > 0 && i) {
      const s = a.sketchViewModel.updateGraphics.getItemAt(0);
      s && (s.set("geometry", i), a.sketchViewModel.update(s));
    }
  }
  async _goToAndWaitForStationary(e) {
    const t = this._updatedMapView;
    t && (await t.goTo(e, {
      animate: !0,
      duration: this.isMobile ? 1200 : 800,
      easing: "ease-in-out"
    }), await f.whenOnce(() => t.stationary));
  }
  async _initializeSketchPoint(e) {
    this.isMobile && await new Promise((s) => setTimeout(s, 1e3));
    const t = this._editor.value?.activeWorkflow, a = t.sketchViewModel.createGraphic.set("geometry", e).clone();
    t.sketchViewModel.addGraphic(a), t.sketchViewModel.emit("create", {
      graphic: a,
      state: "complete",
      toolEventInfo: null,
      type: "create"
    }), await t.sketchViewModel.update(a);
  }
  _getSearchConfig(e, t) {
    const i = e.sources;
    return i && i?.length > 0 ? (i.forEach((a) => {
      if (a.hasOwnProperty("layer")) {
        const r = a, o = r.layer?.id, l = o ? t.map?.findLayerById(o) : "", d = r?.layer?.url;
        l ? r.layer = l : d && (r.layer = new S(d));
      }
    }), i?.forEach((a) => {
      if (a.hasOwnProperty("locator")) {
        const r = a;
        if (r?.name === "ArcGIS World Geocoding Service") {
          const o = r.outFields || ["Addr_type", "Match_addr", "StAddr", "City"];
          r.outFields = o, r.singleLineFieldName = "SingleLine";
        }
        r.url = r.url, delete r.url;
      }
    })) : e = {
      ...e
    }, e;
  }
  _updateSearchActiveSourceIndex() {
    this._searchRef.value && (this._searchRef.value.searchAllDisabled ? this._searchRef.value.activeSourceIndex = 0 : this._searchRef.value.activeSourceIndex = -1);
  }
  async _setFloorLevel(e) {
    if (!e)
      return;
    const t = this._selectedLayer, i = t?.floorInfo?.floorField;
    if (i) {
      const a = t.fields.find((s) => s.name === i);
      if (a && !t?.formTemplate) {
        const r = this._editor.value?.activeWorkflow?.formViewModel;
        r && (await r.setValueForFieldName?.(a.name, e, r.features), a.editable = !1);
      } else if (t.formTemplate && this.formElements) {
        const s = new P({
          expression: `'${e}'`,
          name: "floor-info-test",
          title: "Floor Info",
          returnType: "string"
        }), r = new C({
          label: i,
          editableExpression: "false",
          fieldName: i,
          input: {
            type: "text-box",
            maxLength: 50,
            minLength: 0
          },
          valueExpression: s.name
        });
        this._updatedMapView?.map.editableLayers.forEach((o) => {
          const l = this.formElements.orgElements, d = this.formElements.orgExpressionInfos, m = [...l];
          if (m.push(r), o.type === "feature") {
            const g = o, h = new $({
              title: g?.formTemplate?.title,
              description: g?.formTemplate?.description,
              elements: m,
              expressionInfos: [s].concat(d)
            });
            o.formTemplate = h;
          }
        });
      }
    }
  }
  _setAttributeValuesFromAIAnalysis() {
    this._aiAnalysisInfo?.results && this._aiAnalysisInfo.results.forEach((e) => {
      const i = this._editor?.value?.activeWorkflow?.formViewModel;
      i && e.key && e.key !== _ && e.success && i.setValueForFieldName(e.key, e.value, i.features);
    });
  }
  _getImageExtractionData() {
    const e = [];
    return this.aiImageExtraction?.forEach((t) => {
      t?.field && t.prompt && t.id === this.selectedLayerId && e.push({ key: t.field, context: t.prompt });
    }), e;
  }
  _getTextExtractionData() {
    const e = [];
    return this.aiTextExtraction?.forEach((t) => {
      t?.field && t.prompt && t.id === this.selectedLayerId && e.push({ key: t.field, context: t.prompt });
    }), e;
  }
  _hasImageExtraction() {
    return !!this.aiImageExtraction?.some((e) => e?.field && e.prompt && e.id === this.selectedLayerId);
  }
  _hasTextExtraction() {
    return !!this.aiTextExtraction?.some((e) => e?.field && e.prompt && e.id === this.selectedLayerId);
  }
  _shouldExtractLocationFromText() {
    return !!this.aiTextExtraction?.some((e) => e.id === this.selectedLayerId);
  }
  _getAnalysisErrorMessage(e) {
    const t = this._aiAnalysisInfo?.results?.length || 0;
    return this._analysisMode === "text" ? e && e === t ? this._translations.textExtractionError : this._translations.textExtractionPartialError : e && e === t ? this._translations.imageExtractionError : this._translations.imageExtractionPartialError;
  }
  _getExtractedAddress(e) {
    const t = e.find((i) => i.key === _ && i.success && i.value !== null);
    if (t) {
      if (typeof t.value == "string")
        return t.value.trim() || void 0;
      if (typeof t.value == "object" && typeof t.value.address == "string")
        return t.value.address.trim() || void 0;
    }
  }
  async _geocodeExtractedAddress(e, t) {
    if (!(!this.mapView?.spatialReference || !e))
      try {
        const a = (await T.addressToLocations(t.url, {
          location: this.mapView.center,
          address: { [t.singleLineFieldName]: e },
          outSpatialReference: this.mapView.spatialReference,
          maxLocations: 1
        }))?.[0]?.location;
        return a || void 0;
      } catch (i) {
        console.error("Address geocoding failed", i);
        return;
      }
  }
  _getLocatorConfig() {
    const e = this.searchConfiguration?.sources?.find((a) => "url" in a && !!a.url);
    if (e?.url)
      return {
        url: e.url,
        singleLineFieldName: e.singleLineFieldName || "SingleLine"
      };
    const t = this.mapView?.map?.portalItem?.portal?.helperServices?.geocode;
    return {
      url: Array.isArray(t) ? t[0]?.url : t?.url,
      singleLineFieldName: "SingleLine"
    };
  }
  async hideEditorsElements() {
    if (!this.customizeSubmit || this._editor.value?.state === "editing-attachment" || this._editor.value?.state === "adding-attachment")
      return;
    await this.timeout(800), this.el.querySelector("arcgis-editor")?.shadowRoot?.querySelectorAll("calcite-flow-item")?.forEach((t) => {
      const i = t.shadowRoot?.querySelector("calcite-panel")?.shadowRoot?.querySelector("article");
      i?.querySelector("header")?.setAttribute("style", "display: none"), i?.querySelector("footer")?.setAttribute("style", "display: none");
    });
  }
  async timeout(e) {
    return await new Promise((t) => setTimeout(t, e));
  }
  _removeHandlers() {
    this._drawingHandler?.remove(), this._featureFormHandler?.remove(), this._activeFeatureCountHandler?.remove(), this._layerEditsHandler?.remove();
  }
}
I("create-feature", N);
export {
  N as CreateFeature
};
