import { c as p } from "../../chunks/runtime.js";
import { ref as d } from "lit-html/directives/ref.js";
import _ from "@geoscene/core/widgets/Search/SearchViewModel.js";
import { LitElement as v, createEvent as w, noShadowRoot as f, safeClassMap as n, nothing as S } from "@arcgis/lumina";
import { reEmitEvent as l } from "@arcgis/lumina/controllers/accessor";
import { a as g } from "../../chunks/maybe.js";
import { classes as M } from "@arcgis/components-utils";
import { g as b } from "../../chunks/globalCss.js";
import { isAbortError as C } from "@geoscene/core/core/promiseUtils.js";
import { m as $ } from "../../chunks/useViewModel.js";
import { render as R, html as o } from "lit-html";
import { css as x } from "@lit/reactive-element/css-tag.js";
import { substitute as y } from "@geoscene/core/intl.js";
import { usePropertyChange as T } from "@arcgis/lumina/controllers";
import { u as A } from "../../chunks/useT9n.js";
import { watch as D } from "@geoscene/core/core/reactiveUtils.js";
/*! All material copyright GeoScene, All Rights Reserved, unless otherwise specified.
See https://js.geoscene.cn/4.33/geoscene/copyright.txt for details.
v4.33.18 */
const h = "geoscene-search", u = {
  base: h,
  autocomplete: `${h}__autocomplete`,
  dropdown: `${h}__dropdown`,
  container: `${h}__container`,
  form: `${h}__form`
}, E = x`@layer{geoscene-search{display:block}.geoscene-search{--geoscene-internal-search-width: 240px;display:flex;flex-flow:row nowrap;align-items:center;justify-content:center;width:var(--geoscene-internal-search-width)}.geoscene-search__dropdown{--calcite-color-border-1: var(--calcite-color-border-input);--calcite-dropdown-width: var(--geoscene-internal-search-width);width:31px}.geoscene-search__autocomplete{flex:1}.geoscene-search__container{display:flex;position:relative;flex:1 0 100%;flex-flow:row nowrap;align-items:stretch}.geoscene-search__form{display:flex;flex:1 0;flex-flow:row nowrap;align-items:stretch;margin:0;padding:0}}`, N = $(_);
class I extends v {
  constructor() {
    super(...arguments), this.viewModel = N(this), this._currentLocationValue = "search-use-current-location", this._autocompleteEl = void 0, this._searchResultRendererContainerEl = document.createElement("div"), this._searchResultRendererEl = void 0, this._suggestController = void 0, this._searchController = void 0, this._lastSearchTerm = "", this.messages = A({}), this._setSearchResultRendererRef = (e) => {
      this._searchResultRendererEl = e;
    }, this._locateFailed = !1, this._showNoResults = !1, this.position = "top-left", this.goToOverride = this.viewModel.goToOverride, this.icon = "search", this.activeMenu = "none", this.activeSourceIndex = this.viewModel.activeSourceIndex, this.allPlaceholder = this.viewModel.allPlaceholder, this.allSources = this.viewModel.allSources, this.autoNavigateDisabled = this.viewModel.autoNavigate, this.autoSelectDisabled = this.viewModel.autoSelect, this.defaultSources = this.viewModel.defaultSources, this.disabled = !1, this.includeDefaultSourcesDisabled = this.viewModel.includeDefaultSources, this.locationDisabled = this.viewModel.locationEnabled, this.maxResults = this.viewModel.maxResults, this.maxSuggestions = this.viewModel.maxSuggestions, this.minSuggestCharacters = this.viewModel.minSuggestCharacters, this.popupDisabled = this.viewModel.popupEnabled, this.popupTemplate = this.viewModel.popupTemplate, this.portal = this.viewModel.portal, this.resultGraphic = this.viewModel.resultGraphic, this.resultGraphicDisabled = this.viewModel.resultGraphicEnabled, this.results = this.viewModel.results, this.searchAllDisabled = this.viewModel.searchAllEnabled, this.searchTerm = this.viewModel.searchTerm, this.selectedResult = this.viewModel.selectedResult, this.sources = this.viewModel.sources, this.suggestions = this.viewModel.suggestions, this.suggestionsDisabled = this.viewModel.suggestionsEnabled, this.autoDestroyDisabled = !1, this.state = this.viewModel.state, this.geoscenePropertyChange = T()("state"), this.geosceneReady = w(), this.geosceneSearchClear = l(() => this.viewModel, "search-clear"), this.geosceneSearchComplete = l(() => this.viewModel, "search-complete"), this.geosceneSearchStart = l(() => this.viewModel, "search-start"), this.geosceneSelectResult = l(() => this.viewModel, "select-result"), this.geosceneSuggestComplete = l(() => this.viewModel, "suggest-complete"), this.geosceneSuggestStart = l(() => this.viewModel, "suggest-start");
  }
  static {
    this.properties = { _locateFailed: 16, _showNoResults: 16, _isDisabled: 16, _showCurrentLocation: 16, _effectiveActiveMenu: 16, referenceElement: 1, position: 3, goToOverride: 0, icon: 1, activeMenu: 1, activeSource: 32, activeSourceIndex: 9, allPlaceholder: 1, allSources: 0, autoNavigateDisabled: 5, autoSelectDisabled: 5, defaultSources: 0, disabled: 5, includeDefaultSourcesDisabled: 5, locationDisabled: 5, maxResults: 9, maxSuggestions: 9, minSuggestCharacters: 9, popupDisabled: 5, popupTemplate: 0, portal: 0, resultGraphic: 0, resultGraphicDisabled: 5, results: 0, searchAllDisabled: 5, searchTerm: 1, selectedResult: 0, sources: 0, suggestions: 0, suggestionsDisabled: 5, autoDestroyDisabled: 5, messageOverrides: 0, label: 1, state: 3 };
  }
  static {
    this.styles = E;
  }
  static {
    this.shadowRootOptions = f;
  }
  get _isDisabled() {
    const { state: e } = this.viewModel;
    return e === "disabled" || e === "loading" || this.disabled;
  }
  get _showCurrentLocation() {
    return !this.locationDisabled && !this.searchTerm?.trim();
  }
  get _effectiveActiveMenu() {
    return this._isDisabled ? "none" : this.activeMenu;
  }
  get activeSource() {
    return this.viewModel?.activeSource;
  }
  clear() {
    this._locateFailed = !1, this.viewModel.clear();
  }
  async destroy() {
    await this.manager.destroy(), await this._searchResultRendererEl?.destroy(), this._cancelQueries();
  }
  async search(e) {
    this._cancelQueries();
    const t = new AbortController(), { signal: s } = t;
    this._searchController = t;
    try {
      const i = await this.viewModel.search(e, { signal: s });
      return this._searchController !== t ? void 0 : (i?.numResults || (this._showNoResults = !0, this.activeMenu = "suggestion"), this._searchController = void 0, i);
    } catch {
      if (this._searchController !== t)
        return;
      this._searchController = void 0;
      return;
    }
  }
  async suggest(e) {
    this._cancelSuggest();
    const t = new AbortController(), { signal: s } = t;
    this._suggestController = t;
    try {
      const i = await this.viewModel.suggest(e, null, { signal: s });
      return this._suggestController !== t ? void 0 : (this._suggestController = void 0, i?.numResults && (this.activeMenu = "suggestion", this._scrollToTopSuggestion()), i);
    } catch {
      return this._suggestController !== t || (this._suggestController = void 0), null;
    }
  }
  async setFocus() {
    await this._autocompleteEl?.setFocus();
  }
  loaded() {
    this._addSearchResultRenderer(), this.manager.onLifecycle(() => D(() => this.viewModel?.defaultPopupTemplate, (e) => {
      if (e) {
        const t = document.createElement("div");
        t.appendChild(this._searchResultRendererContainerEl), e.content = t;
      }
    }, { initial: !0 }));
  }
  _addSearchResultRenderer() {
    R(o`<geoscene-search-result-renderer auto-destroy-disabled .messages=${this.messages} .viewModel=${this.viewModel} ${d(this._setSearchResultRendererRef)}></geoscene-search-result-renderer>`, this._searchResultRendererContainerEl);
  }
  _handleInputKeydown(e) {
    e.key === "Tab" && this._cancelSuggest();
  }
  _handleAutocompleteCreate(e) {
    this._autocompleteEl = e;
  }
  _handleCalciteAutocompleteTextInput(e) {
    const s = e.target.inputValue;
    s !== this.viewModel.searchTerm && (this.viewModel.searchTerm = s, s || this.clear(), this.suggest());
  }
  _handleAutocompleteOpen() {
    this.activeMenu = "suggestion";
  }
  _handleAutocompleteClose() {
    this.activeMenu === "suggestion" && (this.activeMenu = "none");
  }
  _handleCalciteAutocompleteChange(e) {
    const t = e.target.value;
    if (t === this._currentLocationValue) {
      this._useCurrentLocation();
      return;
    }
    const s = JSON.parse(t), i = this.viewModel.suggestions?.find(({ sourceIndex: r }) => r === s.sourceIndex)?.results?.find(({ key: r }) => `${r}` == `${s.key}`);
    i && this.search(i);
  }
  async _useCurrentLocation() {
    this._cancelQueries();
    const e = new AbortController(), { signal: t } = e;
    this._searchController = e;
    try {
      await this.viewModel.searchNearby({ signal: t });
    } catch (s) {
      C(s) || (this._locateFailed = !0, this.activeMenu = "suggestion");
    } finally {
      this._searchController = void 0;
    }
  }
  _handleSourceOpen() {
    this.activeMenu = "source";
  }
  _handleSourceClose() {
    this.activeMenu === "source" && (this.activeMenu = "none");
  }
  _handleSourceSelect(e) {
    const i = e.target.selectedItems[0].getAttribute("data-source-index");
    i && (this.viewModel.activeSourceIndex = Number.parseInt(i, 10));
  }
  _cancelSuggest() {
    this.activeMenu = "none", this._locateFailed = !1, this._showNoResults = !1, this._suggestController = g(this._suggestController);
  }
  _cancelQueries() {
    this._cancelSuggest(), this._searchController = g(this._searchController);
  }
  _scrollToTopSuggestion() {
    this._autocompleteEl?.scrollContentTo({ top: 0 });
  }
  _formSubmit(e) {
    e.preventDefault(), this.activeMenu = "none", this._lastSearchTerm = this.searchTerm, this.searchTerm && this.search();
  }
  _getSourceName(e) {
    const { messages: t } = this, { allSources: s } = this.viewModel, i = s.at(e);
    return (e === -1 ? t.all : i?.name || t.untitledSource) || "";
  }
  render() {
    return this._addSearchResultRenderer(), o`<div class=${n(M(u.base, b.widget))}><div class=${n(u.container)}>${this._renderSourcesMenu()}${this._renderForm()}</div></div>`;
  }
  _renderSourcesMenu() {
    const { messages: e, _isDisabled: t, _effectiveActiveMenu: s } = this, { allSources: i, searchAllEnabled: r } = this.viewModel;
    return i.length > 1 ? o`<calcite-dropdown class=${n(u.dropdown)} .disabled=${t} .open=${s === "source"} overlay-positioning=fixed @calciteDropdownClose=${this._handleSourceClose} @calciteDropdownOpen=${this._handleSourceOpen} @calciteDropdownSelect=${this._handleSourceSelect}><calcite-button appearance=outline-fill icon-start=caret-down kind=neutral .label=${e.searchIn} slot=trigger></calcite-button><calcite-dropdown-group .groupTitle=${e.searchIn}>${r ? this._renderSource(-1) : null}${i.map((a, c) => this._renderSource(c)).toArray()}</calcite-dropdown-group></calcite-dropdown>` : null;
  }
  _renderUseCurrentLocation() {
    const { _currentLocationValue: e } = this;
    return o`<calcite-autocomplete-item .heading=${this.messages.useCurrentLocation ?? ""} icon-start=gps-on .value=${e}></calcite-autocomplete-item>`;
  }
  _renderAutocomplete() {
    const { _effectiveActiveMenu: e, messages: t, _isDisabled: s } = this, { maxInputLength: i, placeholder: r, searchTerm: a, state: c } = this.viewModel, m = this.label ?? t.searchButtonTitle ?? "";
    return o`<calcite-autocomplete .autocomplete=${"off"} class=${n(u.autocomplete)} .disabled=${s} .icon=${this.icon} .inputValue=${a} .label=${m} .loading=${c === "searching"} .maxLength=${i} .name=${this.el.id} @keydown=${this._handleInputKeydown} .open=${e === "suggestion"} overlay-positioning=fixed .placeholder=${r} title=${(a ? "" : r) ?? S} @calciteAutocompleteChange=${this._handleCalciteAutocompleteChange} @calciteAutocompleteClose=${this._handleAutocompleteClose} @calciteAutocompleteOpen=${this._handleAutocompleteOpen} @calciteAutocompleteTextChange=${this._handleCalciteAutocompleteTextInput} @calciteAutocompleteTextInput=${this._handleCalciteAutocompleteTextInput} ${d(this._handleAutocompleteCreate)}>${this._renderSuggestions()}${this._renderNotices()}</calcite-autocomplete>`;
  }
  _renderForm() {
    return o`<form class=${n(u.form)} @submit=${this._formSubmit} role=search>${this._renderAutocomplete()}</form>`;
  }
  _renderSuggestGroup(e) {
    return e.results?.map((t) => this._renderSuggestion(t));
  }
  _renderSuggestions() {
    const { suggestions: e } = this.viewModel;
    return this._showNoResults ? null : this._showCurrentLocation ? this._renderUseCurrentLocation() : e?.map((t) => this._renderSuggestResults(t));
  }
  _renderSuggestResults(e) {
    const { allSources: t, activeSourceIndex: s } = this.viewModel, { sourceIndex: i } = e, r = e.results?.length, a = t.length > 1 && s === -1, c = this._getSourceName(i);
    return r && a ? o`<calcite-autocomplete-item-group .heading=${c}>${this._renderSuggestGroup(e)}</calcite-autocomplete-item-group>` : this._renderSuggestGroup(e);
  }
  _renderSuggestion({ key: e, sourceIndex: t, text: s }) {
    const i = {
      key: e,
      sourceIndex: t
    };
    return o`<calcite-autocomplete-item .heading=${s ?? this.messages.untitledResult ?? ""} .value=${JSON.stringify(i)}></calcite-autocomplete-item>`;
  }
  _renderSource(e) {
    const t = this._getSourceName(e);
    return o`<calcite-dropdown-item data-source-index=${`${e}`} .selected=${e === this.viewModel.activeSourceIndex}>${t}</calcite-dropdown-item>`;
  }
  _renderNoResultsWarning(e) {
    const { messages: t } = this, s = e ? y(t.noResultsFoundForValue ?? "", {
      value: `"${e}"`
    }) : t.noResultsFound;
    return o`<calcite-notice icon=exclamation-mark-triangle kind=warning open slot=content-bottom><div slot=title>${t.noResults}</div><div slot=message>${s}</div></calcite-notice>`;
  }
  _renderLocateError() {
    return o`<calcite-notice icon=exclamation-mark-circle kind=danger open slot=content-bottom><div slot=message>${this.messages.locateError}</div></calcite-notice>`;
  }
  _renderNotices() {
    return this._locateFailed ? this._renderLocateError() : this._showNoResults ? this._renderNoResultsWarning(this._lastSearchTerm ?? this.viewModel.searchTerm) : null;
  }
}
p("geoscene-search", I);
export {
  I as GeosceneSearch
};