/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
import { c as v } from "../../chunks/runtime.js";
import { a as b, g as _ } from "../../chunks/mapViewUtils.js";
import { u as M } from "../../chunks/useT9n.js";
import { css as I, html as c, nothing as w } from "lit";
import { createRef as p, ref as m } from "lit-html/directives/ref.js";
import { LitElement as A, createEvent as h, noShadowRoot as L, safeClassMap as f } from "@arcgis/lumina";
import { p as V } from "../../chunks/queryUtils.js";
import x from "@arcgis/core/widgets/Editor";
import k from "@arcgis/core/form/ExpressionInfo";
import F from "@arcgis/core/layers/FeatureLayer";
import S from "@arcgis/core/form/elements/FieldElement";
import E from "@arcgis/core/form/FormTemplate";
import P from "@arcgis/core/views/MapView";
import C from "@arcgis/core/widgets/Home";
import $ from "@arcgis/core/widgets/Search";
import T from "@arcgis/core/Graphic";
import * as g from "@arcgis/core/core/reactiveUtils";
import R from "@arcgis/core/request";
import * as G from "exifr";
import z from "@arcgis/core/geometry/Point";
import U from "@arcgis/core/geometry/SpatialReference";
const H = I`@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%;visibility:hidden}.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}.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;gap:12px;padding:10px;--calcite-card-border-color: var(--calcite-color-border-1)}.cursor-pointer{cursor:pointer}.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}@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}}}`;
class D extends A {
  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._currentPage = "templatePicker", this._editorLoading = !1, this._inValidGeomtryDrawn = !1, this._selectedImageBase64 = "", this._imageAnalysisFailed = !1, this._translations = M({ name: "create-feature", blocking: !0 }), this._addingAttachment = !1, this._uploadedImage = null, this._calciteNotice = p(), this._isSubmitBtnClicked = !1, this._mapViewContainer = p(), this._searchDiv = p(), this._inputImageForAI = p(), this._guidingMessageRefNode = p(), this._abortController = new AbortController(), this.success = h(), this.fail = h(), this.drawComplete = h(), this.editingLocation = h(), this.editingAttachment = h(), this.progressStatus = h(), this.modeChanged = h();
  }
  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, aiImageExtraction: 0, _currentPage: 16, _editorLoading: 16, _inValidGeomtryDrawn: 16, _selectedImageBase64: 16, _imageAnalysisFailed: 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("_editorLoading") && (this.hasUpdated || this._editorLoading !== !1) && this._editorLoadingWatchHandler(this._editorLoading);
  }
  async mapViewWatchHandler() {
    this.mapView && await this.mapView.when(async () => {
      this._imageAnalysisInfo && !this._imageAnalysisInfo.canUseAI && await this.init();
    });
  }
  async isMobileHandler() {
    this.modeChanged.emit();
  }
  async _editorLoadingWatchHandler(e) {
    if (e) {
      if (this._container?.classList.add("display-none"), this._selectedLayer?.isTable) {
        if (this._selectedLayer.templates && this._editor) {
          const i = this._selectedLayer.templates[0], t = {
            layer: this._selectedLayer,
            template: i
          };
          await this._editor.startCreateFeaturesWorkflowAtFeatureCreation(t), await this.hideEditorsElements();
        }
      } else
        await this.startCreate();
      this._container?.classList.remove("display-none"), this._editorLoading = !1;
    }
  }
  async submit() {
    this._editor?.viewModel?.featureFormViewModel && (this._isSubmitBtnClicked = !0, this._editor.viewModel.featureFormViewModel.submit());
  }
  async refresh(e) {
    this._editor && (e ? await this._setFloorLevel(e) : this.reportingArea && this.reportingAreaLayer && this._currentPage !== "drawing" ? await this.queryIntersectingFeatures() : this._currentPage !== "drawing" && (this._inValidGeomtryDrawn = !1, this.drawComplete.emit(this._inValidGeomtryDrawn)));
  }
  async showForm() {
    this.progressStatus.emit(100), this._container?.classList.remove("display-none"), this._mapViewContainer.value?.classList?.replace("show-map", "hide-map"), this._currentPage = "featureForm";
  }
  async load() {
    this._imageAnalysisInfo = await this._getImageAnalysisInfo(), this._currentPage = this._imageAnalysisInfo.canUseAI ? "chooseReportType" : "templatePicker";
  }
  async loaded() {
    this._imageAnalysisInfo && !this._imageAnalysisInfo.canUseAI && await this.init();
  }
  async updated() {
    if (this.isMobile && this.updateMapPosition) {
      const e = this._currentPage === "drawing" ? 80 : 30, i = this.enableSearch ? this._searchDiv.value?.offsetHeight : 0;
      await this._calciteNotice.value?.componentOnReady();
      const a = (this._calciteNotice.value?.offsetHeight || 0) + i + 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 && (this._editor.viewModel.sketchViewModel && this._editor.viewModel.sketchViewModel?.destroy(), this._editor.destroy(), this.enableSnapping && this.mapView?.ui.view && ((this.mapView?.ui.view).grid = null));
  }
  render() {
    const e = this._currentPage === "drawing" || this._currentPage === "editing" ? "" : "display-none", i = this._editorLoading || this._currentPage === "loading" ? "" : "display-none", t = this._editorLoading ? "display-none" : "", a = this.isMobile && this.updateMapPosition ? "show-map" : "display-none", s = this._inValidGeomtryDrawn ? "danger" : "success", r = this._inValidGeomtryDrawn ? "exclamation-mark-triangle" : "lightbulb", o = this.showLayerVisibilityMsg && this._currentPage === "templatePicker", l = (this.showGuidingMsg || o) && this._currentPage !== "loading";
    let n = this._translations.chooseCategoryMsg;
    const d = this._imageAnalysisInfo?.canUseAI && ["chooseReportType", "analyzingImage", "imageUpload"].includes(this._currentPage);
    return this._inValidGeomtryDrawn ? n = this.reportingAreaMessage || this._translations.reportOutsideAreaMessage : this._currentPage === "drawing" || this._currentPage === "editing" ? n = this._translations.provideLocationMsg : this._currentPage === "featureForm" ? n = this._imageAnalysisInfo?.results?.filter((u) => u.success).length ? this._translations.formReviewMsg : this._translations.provideDetailsMsg : o && (n = this._translations.enableFeatureTemplatesMessage), c`${this._imageAnalysisFailed && c`<calcite-alert auto-close icon=x-octagon kind=danger label @calciteAlertClose=${() => {
      this._imageAnalysisFailed = !1;
    }} open placement=top><div slot=title>${this._translations.error}</div><div slot=message>${this._translations.imageExtractionError}</div></calcite-alert>` || ""}${d && c`<calcite-panel>${this._currentPage === "chooseReportType" && this._getReportTypePage() || ""}${this._currentPage === "imageUpload" && this._aiImageExtractionPage() || ""}${this._currentPage === "analyzingImage" && this._getAnalyzingImagePage() || ""}</calcite-panel>` || ""}${!d && c`${l && c`<calcite-notice class="notice-msg" .icon=${r} .kind=${s} open ${m(this._calciteNotice)}><div slot=message .innerHTML=${n ?? ""} ${m(this._guidingMessageRefNode)}></div></calcite-notice>` || ""}${this._selectedImageBase64 && this._currentPage === "featureForm" && c`<div class="image-preview-container"><calcite-label>${this._translations.photo}</calcite-label><img class="width-full" src=${this._selectedImageBase64 ?? w}></div>` || ""}<calcite-loader class=${f(i)} label scale=s></calcite-loader>${this._currentPage === "featureForm" && this.isMobile && c`<calcite-button appearance=transparent class="edit-location-btn" icon-start=pin @click=${this.editLocation}>${this._translations.editLocationLabel}</calcite-button>` || ""}<div class=${f(t)} id=feature-form></div>${this.enableSearch && c`<div class=${`search-widget ${e} ${t}`} id=search-widget-ref ${m(this._searchDiv)}></div>` || ""}` || ""}<div class=${f(a)} ${m(this._mapViewContainer)}></div>`;
  }
  async init() {
    this.mapView && this.selectedLayerId && (this._updatedMapView = this.mapView, await (this.isMobile && this.updateMapPosition ? this.createMobileMapView() : this._loadWidgets()));
  }
  async createMobileMapView() {
    this._mapViewContainer.value && this.mapView && (this._mapViewContainer.value.classList.add("hide-map"), await new P({
      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 i = new C({
        view: this._updatedMapView
      });
      i && this._updatedMapView.ui.add(i, "top-left"), this._loadWidgets();
    }, (e) => {
      console.log(e);
    }));
  }
  async _loadWidgets() {
    await this.createEditorWidget(), this.enableSearch && await this.createSearchWidget();
  }
  _getReportTypePage() {
    return c`<div class="report-selection-container"><calcite-label>${this._translations.createReportHeading}</calcite-label><calcite-card class="cursor-pointer" @click=${() => {
      this.progressStatus.emit(35), this._currentPage = "imageUpload";
    }}><div slot=description class="card-body-content"><calcite-icon icon=effects scale=m style="color: var(--calcite-ui-text-2)"></calcite-icon><div class="text-stack"><span class="option-title">${this._translations.aiImgExtractionLabel}</span><span class="option-description">${this._translations.aiAssistantDescription}</span></div></div></calcite-card><calcite-card class="cursor-pointer" @click=${() => {
      this._currentPage = "templatePicker", this.init();
    }}><div slot=description class="card-body-content"><calcite-icon 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>`;
  }
  _aiImageExtractionPage() {
    const e = this._selectedImageBase64 !== "", i = e ? this._translations.replaceImage : this._translations.imageUploadLimitHint;
    return c`<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} ${m(this._inputImageForAI)}></calcite-input></calcite-label><div class="info-container"><calcite-icon icon=information scale=s></calcite-icon><span>${i}</span></div>${e && c`<img class="width-full" src=${this._selectedImageBase64 ?? w}>` || ""}</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>`;
  }
  _getAnalyzingImagePage() {
    return c`<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>`;
  }
  _onImageUpload(e) {
    const i = e.target;
    if (i) {
      const t = i.files[0], a = new FileReader();
      a.onload = (s) => {
        this._selectedImageBase64 = s.target?.result;
      }, t ? (a.readAsDataURL(t), this._uploadedImage = t) : (this._selectedImageBase64 = "", this._uploadedImage = null);
    }
  }
  async _analyzeImage() {
    this._abortController = new AbortController();
    const e = this._abortController.signal, i = await this._getImageAnalysisInfo();
    if (!i.canUseAI || !i.url || !this._inputImageForAI.value?.files?.length) {
      this._imageAnalysisFailed = !0, console.error(this._translations.error), this._resetImageAnalysisInfo(), await this.init();
      return;
    }
    try {
      this._currentPage = "analyzingImage", this.progressStatus.emit(45);
      const t = 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(t);
      });
      if (this.enablePhotoLocation) {
        const r = await G.gps(t);
        if (r?.longitude && r.latitude && this.mapView?.spatialReference) {
          const o = new z({
            longitude: r.longitude,
            latitude: r.latitude,
            spatialReference: new U({ wkid: 4326 })
          }), l = await V(o, this.mapView.spatialReference);
          this._imageAnalysisInfo && (this._imageAnalysisInfo.imageLocation = l);
        }
      }
      const s = [];
      if (this.aiImageExtraction?.forEach((r) => {
        r?.field && r.prompt && r.id === this.selectedLayerId && s.push({ key: r.field, context: r.prompt });
      }), s.length) {
        const r = {
          input: a,
          data: s
        }, o = await R(i.url, {
          method: "post",
          headers: {
            "Content-Type": "application/json",
            "x-esri-authorization": `Bearer ${i.token}`,
            "x-esri-request-source": `instantapps/${this.appName}`
          },
          body: JSON.stringify(r),
          responseType: "json",
          signal: e
        });
        this._imageAnalysisInfo && (this._imageAnalysisInfo.results = o.data.results);
      }
      this._currentPage = "loading", await this.init();
    } catch (t) {
      t.name === "AbortError" ? console.error("Aborted", t) : (this._imageAnalysisFailed = !0, console.error("Analyzing failed", t)), this._resetImageAnalysisInfo(), this.init();
    }
  }
  _resetImageAnalysisInfo() {
    const e = {
      url: "",
      token: "",
      canUseAI: !1,
      imageLocation: void 0,
      results: []
    };
    this._selectedImageBase64 = "", this._imageAnalysisInfo = e;
  }
  async _getImageAnalysisInfo() {
    const e = {
      url: "",
      token: "",
      canUseAI: !1
    };
    if (this.aiImageExtraction?.some((t) => t?.field && t.prompt && t.id === this.selectedLayerId)) {
      const t = (this.mapView?.map).portalItem.portal;
      if (t) {
        const a = await t.fetchSettings(), s = t?.helperServices.aiUtilityServices;
        s?.url && s?.api?.image_analyze && (e.url = s.url + s.api.image_analyze), t.credential && (e.token = t.credential.token), a?.aiAssistantsEnabled && !a.blockBetaApps && t?.user?.privileges?.includes("portal:user:useAIAssistants") && (e.canUseAI = !0);
      }
    }
    return e;
  }
  async createEditorWidget() {
    this._editor && this._editor.destroy();
    const e = [];
    this._container = document.createElement("div"), this._container?.classList.add("display-none"), this.enableSnapping || this._container.classList.add("hide-editor-toolbar");
    const i = this._updatedMapView && await b(this._updatedMapView), t = this.mapView && await _(this.mapView, this.selectedLayerId);
    if (t && (this._selectedLayer = t, !this._selectedLayer?.isTable && i && i.forEach((a) => {
      e.push({
        layer: a,
        enabled: a?.type === "feature" && a?.id === this.selectedLayerId,
        addEnabled: !0,
        // default is true, set to false to disable the ability to add a new feature
        updateEnabled: !1,
        // if true, enable ability to edit an existing feature
        deleteEnabled: !1
        // default is true, set to false to disable the ability to delete features
      });
    })), this._editor = new x({
      view: this._updatedMapView,
      layerInfos: e,
      visibleElements: {
        settingsMenu: this.enableSnapping,
        snappingControls: this.enableSnapping,
        createFeaturesSection: !0,
        editFeaturesSection: !1,
        flow: !0,
        sketch: this.showSketchWidgets && this._selectedLayer?.geometryType !== "point"
      },
      container: this._container
    }), this._mapViewContainer.value ? this.el.insertBefore(this._container, this._mapViewContainer.value) : this.el.appendChild(this._container), this._selectedLayer?.isTable && (this._editorLoading = !0), this._editor) {
      const a = g.watch(() => this._editor?.viewModel.state, (n) => {
        n === "adding-attachment" || n === "editing-attachment" ? (this._addingAttachment = !0, this.editingAttachment.emit(!0)) : this._addingAttachment && (this.editingAttachment.emit(!1), this._addingAttachment = !1);
      });
      a && this._editor.viewModel.addHandles(a);
      const s = g?.watch(() => this._editor?.viewModel.featureTemplatesViewModel.state, (n) => {
        n === "ready" && this._editor?.viewModel?.activeWorkflow?.type !== "create-features" && (this.progressStatus.emit(50), this._editorLoading = !0);
      });
      s && this._editor.viewModel.addHandles(s);
      const r = g?.watch(() => this._editor?.viewModel.featureFormViewModel?.state, (n) => {
        n === "ready" && this._editor?.viewModel.featureFormViewModel && this._currentPage !== "editing" && (this._mapViewContainer.value?.classList?.replace("show-map", "hide-map"), this._editor.viewModel.featureFormViewModel.addHandles(this._editor.viewModel.featureFormViewModel.on("submit", this.submitted.bind(this))), setTimeout(() => {
          this._setFloorLevel(this.floorLevel), this._imageAnalysisInfo?.results && this._setAttributeValuesFromImageAnalysis();
        }, 200), !this.allowMultipleCreation && this._editor.activeWorkflow && (this._editor.activeWorkflow.data.creationInfo.maxFeatures = 1), this._currentPage = "featureForm", this.progressStatus.emit(100), this.drawComplete.emit(!1));
      });
      r && this._editor.viewModel.addHandles(r);
      const o = g.watch(() => this._editor?.viewModel.state, (n) => {
        n === "creating-features" && this._editor?.viewModel.featureFormViewModel && this._editor.viewModel.featureFormViewModel.state === "disabled" && (this._mapViewContainer.value?.classList.replace("hide-map", "show-map"), this._selectedLayer && !this._selectedLayer.isTable && (this._currentPage = "drawing", this._editor.viewModel.sketchViewModel?.createGraphic && this._imageAnalysisInfo?.imageLocation && (this._updatedMapView?.goTo({ center: this._imageAnalysisInfo.imageLocation }), this._selectedLayer.geometryType === "point" && this._initializeSketchPoint(this._imageAnalysisInfo.imageLocation.clone()))));
      });
      o && this._editor.viewModel.addHandles(o), this._editor.on("sketch-create", async (n) => {
        n.detail.state === "complete" && (this._drawnGeometry = n.detail.graphic?.geometry, this.reportingArea && this.reportingAreaLayer && await this.queryIntersectingFeatures());
      });
      let l;
      this._editor.on("sketch-update", (n) => {
        clearTimeout(l), l = window.setTimeout(async () => {
          this._drawnGeometry = n.detail.graphics[0].geometry, this.reportingArea && this.reportingAreaLayer && await this.queryIntersectingFeatures();
        }, 50);
      });
    }
  }
  async queryIntersectingFeatures() {
    const e = this.mapView && await _(this.mapView, this.reportingAreaLayer);
    if (e) {
      const i = e.createQuery();
      i.geometry = this._drawnGeometry, i.spatialRelationship = "intersects";
      const a = await e.queryFeatureCount(i) === 0;
      this._inValidGeomtryDrawn = a, this.drawComplete.emit(this._inValidGeomtryDrawn);
    }
  }
  editLocation() {
    this.progressStatus.emit(75), this.editingLocation.emit(), this._container?.classList.add("display-none"), this._mapViewContainer.value?.classList.replace("hide-map", "show-map"), this._currentPage = "editing";
  }
  async startCreate() {
    return await this.hideEditorsElements(), new Promise((e, i) => {
      if (this._editor?.viewModel.featureTemplatesViewModel.items?.length) {
        const t = this._editor.viewModel.featureTemplatesViewModel.items[0].items;
        this._editor.viewModel.featureTemplatesViewModel.addHandles(this._editor.viewModel.featureTemplatesViewModel.on("select", () => {
          this.progressStatus.emit(75), setTimeout(() => {
            this.hideEditorsElements().then(() => {
              e({});
            }, (s) => i(s));
          }, 700);
        })), t.length === 1 && this._editor.viewModel.featureTemplatesViewModel.select(t[0]);
        const a = t.length > 1;
        this.hideEditorsElements().then(() => {
          a && (this._currentPage = "templatePicker", e({}));
        }, (s) => a && i(s));
      }
    });
  }
  async createSearchWidget() {
    if (this._updatedMapView) {
      let e = {
        view: this._updatedMapView
      };
      if (this.searchConfiguration && (e = {
        ...this._getSearchConfig(this.searchConfiguration, this._updatedMapView)
      }), this._search = new $(e), !this._search)
        return;
      this._search.container = "search-widget-ref", this._search.popupEnabled = !1, this._search.resultGraphicEnabled = !1;
      let i;
      this._search.viewModel.addHandles(this._search.on("search-complete", (a) => {
        a.results[0].results && a.results[0].results[0] && (a.results[0].results[0].extent && this._updatedMapView?.goTo(a.results[0].results[0].extent), this._selectedLayer?.geometryType === "point" && (i = a.results[0].results[0]?.feature.geometry));
      }));
      const t = g.watch(() => this._search?.viewModel.state, (a) => {
        a === "ready" && setTimeout(() => {
          if (this._editor?.viewModel.sketchViewModel?.createGraphic && i)
            this._initializeSketchPoint(i);
          else if (this._editor?.viewModel.sketchViewModel && this._editor.viewModel.sketchViewModel.updateGraphics.length > 0 && i) {
            const s = this._editor?.viewModel.sketchViewModel?.updateGraphics.getItemAt(0);
            s && (s.set("geometry", i), this._editor?.viewModel.sketchViewModel?.update(s), this.hideEditorsElements());
          }
        }, 100);
      });
      t && this._search.viewModel.addHandles(t);
    }
  }
  async _initializeSketchPoint(e) {
    if (this._editor?.viewModel.sketchViewModel?.createGraphic) {
      const t = this._editor.viewModel.sketchViewModel.createGraphic.set("geometry", e).clone();
      this._editor.viewModel.sketchViewModel.addGraphic(t), this._editor.viewModel.sketchViewModel.emit("create", {
        graphic: t,
        state: "complete",
        toolEventInfo: null,
        type: "create"
      }), await this._editor.viewModel.sketchViewModel.update(t), this.hideEditorsElements();
    }
  }
  _getSearchConfig(e, i) {
    const t = "includeDefaultSources", a = e.sources;
    return a && a?.length > 0 ? (e[t] = !1, a.forEach((s) => {
      if (s.hasOwnProperty("layer")) {
        const o = s, l = o.layer?.id, n = l ? i.map?.findLayerById(l) : "", d = o?.layer?.url;
        n ? o.layer = n : d && (o.layer = new F(d));
      }
    }), a?.forEach((s) => {
      if (s.hasOwnProperty("locator")) {
        const o = s;
        if (o?.name === "ArcGIS World Geocoding Service") {
          const l = o.outFields || ["Addr_type", "Match_addr", "StAddr", "City"];
          o.outFields = l, o.singleLineFieldName = "SingleLine";
        }
        o.url = o.url, delete o.url;
      }
    })) : e = {
      ...e,
      includeDefaultSources: !0
    }, e;
  }
  async _setFloorLevel(e) {
    if (!e)
      return;
    const i = this._selectedLayer, t = i?.floorInfo?.floorField;
    if (t) {
      const a = i.fields.find((s) => s.name === t);
      if (a && !i?.formTemplate)
        this._editor?.viewModel.featureFormViewModel && (this._editor.viewModel.featureFormViewModel.setValue(a.name, e), a.editable = !1);
      else if (i.formTemplate && this.formElements) {
        const s = new k({
          expression: `'${e}'`,
          name: "floor-info-test",
          title: "Floor Info",
          returnType: "string"
        }), r = new S({
          label: t,
          editableExpression: "false",
          fieldName: t,
          input: {
            type: "text-box",
            maxLength: 50,
            minLength: 0
          },
          valueExpression: s.name
        });
        this._updatedMapView?.map.editableLayers.forEach((o) => {
          const l = this.formElements.orgElements, n = this.formElements.orgExpressionInfos, d = [...l];
          if (d.push(r), o.type === "feature") {
            const u = o, y = new E({
              title: u?.formTemplate?.title,
              description: u?.formTemplate?.description,
              elements: d,
              expressionInfos: [s].concat(n)
            });
            o.formTemplate = y;
          }
        });
      }
    }
  }
  _setAttributeValuesFromImageAnalysis() {
    this._imageAnalysisInfo?.results && this._imageAnalysisInfo.results.forEach((e) => {
      this._editor?.viewModel.featureFormViewModel && e.key && e.success && this._editor.viewModel.featureFormViewModel.setValue(e.key, e.value);
    });
  }
  async hideEditorsElements() {
    this.customizeSubmit && (await this.timeout(700), this.el.querySelector(".esri-editor")?.querySelectorAll("calcite-flow-item")?.forEach((e) => {
      const i = e.shadowRoot?.querySelector("calcite-panel")?.shadowRoot?.querySelector("article");
      i?.querySelector("header")?.setAttribute("style", "display: none"), i?.querySelector("footer")?.setAttribute("style", "display: none");
    }));
  }
  async submitted(e) {
    let i = !1;
    if (e.invalid.length) {
      this._isSubmitBtnClicked = !1;
      return;
    }
    if (this._isSubmitBtnClicked) {
      this._isSubmitBtnClicked = !1;
      try {
        if (this._editor?.activeWorkflow) {
          if (this._selectedLayer && this._selectedLayer.capabilities.data.supportsAttachment && this._selectedImageBase64 && (i = !0), i) {
            const t = this._selectedLayer?.on("edits", async (a) => {
              if (a.addedFeatures.length > 0) {
                const s = a.addedFeatures[0].objectId;
                try {
                  if (this._uploadedImage && this._selectedLayer) {
                    const r = this._uploadedImage, o = new FormData();
                    o.set("keywords", "ai-image"), o.set("attachment", r), o.append("f", "json");
                    const l = new T({
                      attributes: {
                        [this._selectedLayer.objectIdField]: s
                      }
                    });
                    await this._selectedLayer.addAttachment(l, o);
                  }
                } catch (r) {
                  console.error("Attachment upload failed", r);
                }
                t?.remove(), this.success.emit();
              }
            });
          }
          await this._editor.activeWorkflow.commit(), this._editor.viewModel.failures?.length && this._editor.viewModel.failures.some((t) => {
            if (t.error)
              throw t.error;
          });
        }
      } catch (t) {
        this.fail.emit(t);
        return;
      }
      i || this.success.emit();
    }
  }
  async timeout(e) {
    return new Promise((i) => setTimeout(i, e));
  }
}
v("create-feature", D);
export {
  D as CreateFeature
};
