/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { c as y } from "../../chunks/runtime.js";
import { keyed as F } from "lit/directives/keyed.js";
import { LitElement as w, createEvent as n, renderElement as $, nothing as d, safeStyleMap as g, safeClassMap as S } from "@arcgis/lumina";
import { createRef as r, ref as h } from "lit/directives/ref.js";
import { html as l, css as C } from "lit";
import { Task as v } from "@lit/task";
import { log as u, composeMissingPropertyMessage as k } from "@arcgis/toolkit/log";
import { i as B } from "../../chunks/commonFunctions.js";
import { F as f } from "../../chunks/types.js";
import { u as x } from "../../chunks/useT9n.js";
const o = /* @__PURE__ */ new Map();
o.set("oid", "key");
o.set("guid", "key");
o.set("global-id", "key");
o.set("blob", "binary");
o.set("integer", "integer");
o.set("small-integer", "integer");
o.set("big-integer", "integer");
o.set("single", "number");
o.set("double", "number");
o.set("long", "number");
o.set("number", "number");
o.set("date", "date-time");
o.set("date-only", "calendar");
o.set("time-only", "clock");
o.set("timestamp-offset", "time-zone");
o.set("string", "string");
const b = ({ fieldType: p }) => l`<calcite-icon scale=s .icon=${o.get(p)}></calcite-icon>`, L = C`.panel{min-height:250px}.content{max-height:50vh}.field-icons{display:flex;align-items:center;padding:0 var(--calcite-space-sm)}.selection-button-div{padding:var(--calcite-space-2xs) var(--calcite-space-sm-plus)}.no-match-text{padding:var(--calcite-space-md)}.footer{width:100%}.add-cancel-buttons{display:flex;align-content:space-between}`;
class E extends w {
  constructor() {
    super(...arguments), this._messages = x({ blocking: !0 }), this.popoverNode = r(), this.listNode = r(), this.flowElement = r(), this.panelElement = r(), this.dropdownNode = r(), this.fieldInfoFlowItemEl = r(), this.allLists = [], this.filterText = "", this.panelCutOffHeight = 0, this._propWatcherTask = new v(this, {
      task: async ([e]) => {
        if (!this.listOnly && !B(e?.refElement))
          throw u("error", this, k("popoverProps")), new Error();
        this._propWatcherTask.autoRun = !1;
      },
      args: () => [this.popoverProps]
    }), this.fields = [], this.selectedFields = [], this.listOnly = !1, this.showFieldInfo = !1, this.showFieldTypeIcon = !1, this.showFieldName = !1, this.showDescription = !1, this.showSelectionAll = !1, this.showCancel = !0, this.hideCancel = !1, this.showSort = !0, this.hideSort = !1, this.showFilterLength = 10, this.multiple = !1, this.sortBy = "default", this.groupFieldsAndExpressions = !1, this.arcgisChange = n(), this.arcgisClose = n(), this.arcgisFieldPickListChange = n(), this.arcgisFieldPickListDismissed = n(), this.arcgisFieldPickListSortByChange = n(), this.arcgisSortByChange = n(), this.arcgisEditField = n(), this.arcgisDeleteField = n();
  }
  static {
    this.properties = { lastSortBy: 16, filterFields: 16, mapView: 0, view: 0, layer: 0, fields: 0, selectedFields: 0, listOnly: 5, popoverProps: 0, showFieldInfo: 5, showFieldTypeIcon: 5, showFieldName: 5, showDescription: 5, showSelectionAll: 5, showCancel: 5, hideCancel: 5, showSort: 5, hideSort: 5, showFilterLength: 9, multiple: 5, heading: 1, okBtnText: 1, filterPlaceholderText: 1, filterNoResultsText: 1, sortBy: 1, groupFieldsAndExpressions: 5, fieldsGroupHeading: 1, expressionsGroupHeading: 1, customExpressionCheck: 0 };
  }
  static {
    this.styles = L;
  }
  async reposition() {
    await this.popoverNode.value?.reposition();
  }
  async setFocus() {
    setTimeout(() => requestAnimationFrame(() => {
      this.listOnly ? this.listNode.value?.setFocus() : this.panelElement.value?.setFocus();
    }), 1);
  }
  async setDisabled(e) {
    this.panelElement.value && (this.panelElement.value.disabled = e);
  }
  load() {
    !this.view && this.mapView && (this.view = this.mapView), !this.showCancel && !this.hideCancel && (this.hideCancel = !0), !this.showSort && !this.hideSort && (this.hideSort = !0), this.listOnly && this.showFieldInfo && (this.showFieldInfo = !1, u("info", this, "showFieldInfo is not supported if listOnly is true.")), !this.multiple && this.selectedFields.length > 1 && (this.selectedFields = [this.selectedFields[0]]), this.lastSortBy = this.sortBy ?? this.lastSortBy, this.updateGroupedLists();
  }
  willUpdate(e) {
    (e.has("fields") || e.has("lastSortBy") || e.has("customExpressionCheck")) && this.updateGroupedLists();
  }
  loaded() {
    this.setUpObserver(), this.listOnly ? this.listNode.value?.setFocus() : (this.flowElement.value?.setFocus(), this.checkMaxHeight());
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this.observer?.disconnect();
  }
  setUpObserver() {
    this.observer = new MutationObserver((e) => {
      for (const t of e)
        t.attributeName === "style" && this.popoverNode.value && this.dropdownNode.value && this.popoverNode.value.style.visibility === "hidden" && (this.dropdownNode.value.open = !1);
    });
  }
  checkMaxHeight() {
    setTimeout(() => this.checkPanelMaxHeight(), 200), setTimeout(() => this.checkPanelMaxHeight(), 500), setTimeout(() => this.checkPanelMaxHeight(), 1e3), setTimeout(() => this.checkPanelMaxHeight(), 1500);
  }
  checkPanelMaxHeight() {
    if (this.panelCutOffHeight === 0) {
      const e = this.panelElement.value?.getBoundingClientRect();
      if (e && e.bottom > window.innerHeight) {
        this.panelCutOffHeight = e.height - (e.bottom - window.innerHeight) - 5;
        const t = this.listNode.value?.getBoundingClientRect();
        t && (this.listNode.value.style.maxHeight = `${t.height - (e.bottom - window.innerHeight) - 5}px`);
      }
    }
  }
  getSortedList(e) {
    let t = [...e];
    const s = t.filter((i) => i.type === "none");
    return t = t.filter((i) => i.type !== "none"), this.lastSortBy === "display" ? t.sort((i, a) => i.alias.localeCompare(a.alias)) : this.lastSortBy === "field" ? t.sort((i, a) => i.name.localeCompare(a.name)) : this.lastSortBy === "type" && t.sort((i, a) => i.type.localeCompare(a.type)), t = t.concat(s), t;
  }
  isExpression(e) {
    return this.customExpressionCheck ? this.customExpressionCheck(e) : e.name.includes(f.expression);
  }
  canDeselectAll() {
    const e = this.getAllFields();
    return this.filterFields?.length ? this.filterContainsAll() : this.selectedFields.length === e.length;
  }
  filterContainsAll() {
    return !!this.filterFields?.every((e) => this.selectedFields.some((t) => t === e));
  }
  showFieldInfoCheck(e) {
    const { layer: t } = this;
    return this.showFieldInfo ? !(!t || this.isExpression(e) || e.name.includes(f.relationship) || e.type === "none") : !1;
  }
  updateGroupedLists() {
    if (!this.fields)
      return;
    if (this.allLists = [], this.usingCustomGroups())
      for (const t of this.fields)
        this.allLists.push({
          title: t.title,
          fields: [...this.getSortedList(t.fields)]
        });
    else
      this.allLists = this.groupFieldsAndExpressions ? [
        {
          title: this.expressionsGroupHeading,
          fields: [...this.getSortedList(this.fields)].filter((t) => this.isExpression(t))
        },
        {
          title: this.fieldsGroupHeading,
          fields: [...this.getSortedList(this.fields)].filter((t) => !this.isExpression(t))
        }
      ] : [
        {
          title: void 0,
          fields: [...this.getSortedList(this.fields)]
        }
      ];
  }
  addFieldInfoFlowItem(e, t) {
    const s = this.flowElement.value, i = $(l`<calcite-flow-item selected .heading=${e.alias ?? e.name} .description=${e.name} class="panel" style=${g(this.panelCutOffHeight > 0 ? `max-height: ${this.panelCutOffHeight}px` : "max-height: 50vh")} @calciteFlowItemBack=${(a) => {
      a.currentTarget.remove(), this.fieldInfoFlowItemEl.value.selected = !1, this.panelElement.value.selected = !0, setTimeout(() => {
        t.setFocus();
      }, 300);
    }} ${h(this.fieldInfoFlowItemEl)}><arcgis-field-info lang=${this._messages._lang ?? d} .fieldName=${e.name} .layer=${this.layer} .view=${this.view} class="content"></arcgis-field-info></calcite-flow-item>`);
    s.appendChild(i), this.panelElement.value.selected = !1, this.fieldInfoFlowItemEl?.value.setFocus();
  }
  usingCustomGroups() {
    return !!this.fields.length && "fields" in this.fields[0];
  }
  getAllFields() {
    return this.allLists.map((e) => e.fields).flat();
  }
  render() {
    return this._propWatcherTask.render({
      complete: () => {
        if (this.listOnly)
          return this.renderList();
        const e = this.heading || (this.multiple ? this._messages.headerSelect : this._messages.header), t = this.popoverProps;
        return this.el.classList.add("js-app-flyout"), l`<calcite-popover .placement=${t.placement ?? "leading-start"} open pointer-disabled .referenceElement=${t.refElement} .offsetDistance=${t.offsetDistance ?? -Math.round(t.refElement.getBoundingClientRect().width)} .offsetSkidding=${t.offsetSkidding ?? 0} .overlayPositioning=${t.overlayPositioning} trigger-disabled .autoClose=${t.autoClose} .label=${this.heading ?? (this.multiple ? this._messages.headerSelect : this._messages.header) ?? ""} @calcitePopoverClose=${() => {
          this.arcgisClose.emit(), this.arcgisFieldPickListDismissed.emit();
        }} ${h(this.popoverNode)}><calcite-flow style=${g({
          width: `${t.popoverWidth ?? t.refElement.getBoundingClientRect().width}px`,
          ...t.maxHeight && { maxHeight: t.maxHeight }
        })} ${h(this.flowElement)}><calcite-flow-item class="panel" .heading=${e} closable @calciteFlowItemClose=${() => {
          this.arcgisClose.emit(), this.arcgisFieldPickListDismissed.emit();
        }} ${h(this.panelElement)}><slot slot=content-top name=content-top></slot>${this.renderList()}<slot slot=content-bottom name=content-bottom></slot>${(this.multiple || !this.hideCancel) && l`<div slot=footer class="footer"><slot name=content-footer></slot>${this.multiple && !this.hideCancel ? l`<div class="add-cancel-buttons">${this.renderAddButton()}${this.renderCancelButton()}</div>` : l`${this.renderAddButton()}${this.renderCancelButton()}`}</div>` || ""}</calcite-flow-item></calcite-flow></calcite-popover>`;
      },
      error: () => ""
    });
  }
  renderList() {
    const e = this.heading || (this.multiple ? this._messages.headerSelect : this._messages.header), t = this.getAllFields(), s = t.length >= this.showFilterLength;
    return l`${t.length ? l`<calcite-list .label=${e} .selectionMode=${this.multiple ? "multiple" : "single"} class=${S(this.listOnly ? "" : "content")} .filterEnabled=${s} .filterPlaceholder=${this.filterPlaceholderText ?? this._messages.filter} @calciteListChange=${() => {
      const i = this.listNode.value.selectedItems.map((c) => c.value), a = this.selectedFields.filter((c) => i.includes(c)), m = i.filter((c) => !this.selectedFields.includes(c));
      this.selectedFields = [.../* @__PURE__ */ new Set([...a, ...m])], this.arcgisChange.emit({ selectedFields: this.selectedFields }), this.arcgisFieldPickListChange.emit({ selectedFields: this.selectedFields }), this.multiple || (this.arcgisClose.emit({ selectedFields: this.selectedFields }), this.arcgisFieldPickListDismissed.emit({ selectedFields: this.selectedFields }));
    }} @calciteListFilter=${(i) => {
      i.stopPropagation(), this.filterFields = this.listNode.value.filteredItems?.map((a) => a.value), this.filterText = this.listNode.value.filterText;
    }} ${h(this.listNode)}>${this.renderSortButton()}<slot name=content-center></slot>${this.multiple && this.showSelectionAll && (!s || !this.filterText || this.filterFields?.length) ? this.renderSelectionButton() : null}${this.renderListItems()}</calcite-list>` : l`<slot name=no-fields></slot>`}${this.filterFields && !this.filterFields.length && this.listNode.value && this.filterNoResultsText?.length !== 0 ? l`<div class="no-match-text">${this.filterNoResultsText ?? this._messages.noMatches}</div>` : null}`;
  }
  renderSortButton() {
    const e = this.getAllFields();
    if (!(e.length >= this.showFilterLength && !this.hideSort))
      return "";
    const s = e.every((i) => !!i.type);
    return l`<calcite-dropdown slot=filter-actions-end placement=bottom-end overlay-positioning=fixed .disabled=${this.filterFields ? this.filterFields.length < 4 : !1} @calciteDropdownOpen=${() => {
      this.observer?.disconnect(), this.popoverNode.value && this.observer?.observe(this.popoverNode.value, { attributes: !0 });
    }} @calciteDropdownClose=${() => this.observer?.disconnect()} ${h(this.dropdownNode)}><calcite-action slot=trigger .text=${this._messages.sort ?? ""} title=${this._messages.sort ?? d}><calcite-icon scale=s icon=sortDescending flip-rtl></calcite-icon></calcite-action><calcite-dropdown-group><calcite-dropdown-item .selected=${this.lastSortBy === "default"} @click=${() => {
      this.lastSortBy = "default", this.arcgisSortByChange.emit(this.lastSortBy), this.arcgisFieldPickListSortByChange.emit(this.lastSortBy);
    }} @keydown=${(i) => {
      i.stopPropagation(), (i.key === " " || i.key === "Enter") && (this.lastSortBy = "default", this.arcgisSortByChange.emit(this.lastSortBy), this.arcgisFieldPickListSortByChange.emit(this.lastSortBy));
    }}>${this._messages.default}</calcite-dropdown-item><calcite-dropdown-item .selected=${this.lastSortBy === "display"} @click=${() => {
      this.lastSortBy = "display", this.arcgisSortByChange.emit(this.lastSortBy), this.arcgisFieldPickListSortByChange.emit(this.lastSortBy);
    }} @keydown=${(i) => {
      i.stopPropagation(), (i.key === " " || i.key === "Enter") && (this.lastSortBy = "display", this.arcgisSortByChange.emit(this.lastSortBy), this.arcgisFieldPickListSortByChange.emit(this.lastSortBy));
    }}>${this._messages.displayName}</calcite-dropdown-item>${s && l`<calcite-dropdown-item .selected=${this.lastSortBy === "type"} @click=${() => {
      this.lastSortBy = "type", this.arcgisSortByChange.emit(this.lastSortBy), this.arcgisFieldPickListSortByChange.emit(this.lastSortBy);
    }} @keydown=${(i) => {
      i.stopPropagation(), (i.key === " " || i.key === "Enter") && (this.lastSortBy = "type", this.arcgisSortByChange.emit(this.lastSortBy), this.arcgisFieldPickListSortByChange.emit(this.lastSortBy));
    }}>${this._messages.type}</calcite-dropdown-item>` || ""}<calcite-dropdown-item .selected=${this.lastSortBy === "field"} @click=${() => {
      this.lastSortBy = "field", this.arcgisSortByChange.emit(this.lastSortBy), this.arcgisFieldPickListSortByChange.emit(this.lastSortBy);
    }} @keydown=${(i) => {
      i.stopPropagation(), (i.key === " " || i.key === "Enter") && (this.lastSortBy = "field", this.arcgisSortByChange.emit(this.lastSortBy), this.arcgisFieldPickListSortByChange.emit(this.lastSortBy));
    }}>${this._messages.fieldName}</calcite-dropdown-item></calcite-dropdown-group></calcite-dropdown>`;
  }
  renderSelectionButton() {
    return l`<div class="selection-button-div"><calcite-button appearance=transparent scale=s width=full @click=${() => {
      if (this.canDeselectAll())
        this.selectedFields = this.filterFields?.length ? this.selectedFields.filter((e) => !this.filterFields?.includes(e)) : [];
      else if (this.filterFields?.length)
        this.selectedFields = [.../* @__PURE__ */ new Set([...this.selectedFields, ...this.filterFields])];
      else {
        const t = this.getAllFields();
        this.selectedFields = t.map((s) => s.name);
      }
      this.arcgisChange.emit({ selectedFields: this.selectedFields }), this.arcgisFieldPickListChange.emit({ selectedFields: this.selectedFields });
    }}>${this.canDeselectAll() ? this._messages.deselectAll : this._messages.selectAll}</calcite-button></div>`;
  }
  renderListItems() {
    const e = this.allLists.filter((t) => !!t.fields.length);
    return e.length === 1 && !e[0].title ? e[0].fields.map((t) => this.renderCalciteListItem(t)) : e.map((s) => l`<calcite-list-item-group .heading=${s.title}>${s.fields.map((i) => this.renderCalciteListItem(i))}</calcite-list-item-group>`);
  }
  renderCalciteListItem(e) {
    const t = this.showFieldInfoCheck(e), s = this.showFieldTypeIcon && !!e.type;
    return F(e.name, l`<calcite-list-item .label=${e.alias || e.name} .description=${(() => {
      if (this.showFieldName && e.hideFieldName !== !0)
        return `{${e.name}}`;
      if (this.showDescription && e.hideDescription !== !0 && e.description)
        return e.description;
    })()} .value=${e.name} .selected=${!this.multiple && e.name === this.selectedFields[0] || this.multiple && this.selectedFields.includes(e.name)} .metadata=${{
      label: e.alias,
      fieldName: e.name
    }}>${s && l`<div slot=actions-end class="field-icons">${b({ fieldType: e.type })}</div>` || ""}${this.renderInfoAction(e, t)}${this.renderEditAction(e)}${this.renderDeleteAction(e)}</calcite-list-item>`);
  }
  renderInfoAction(e, t) {
    const { _messages: s } = this;
    return t ? l`<calcite-action slot=actions-end .text=${s.info} title=${s.info ?? d} scale=s icon=information @click=${(i) => {
      i.stopPropagation();
      const a = i.currentTarget;
      this.addFieldInfoFlowItem(e, a);
    }}></calcite-action>` : "";
  }
  renderEditAction(e) {
    const { _messages: t } = this;
    return e.showEditAction ? l`<calcite-action slot=actions-end .text=${t.edit} title=${t.edit ?? d} scale=s icon=pencil @click=${(s) => {
      s.stopPropagation(), this.arcgisEditField.emit({ fieldName: e.name });
    }}></calcite-action>` : "";
  }
  renderDeleteAction(e) {
    const { _messages: t } = this;
    return e.showDeleteAction ? l`<calcite-action slot=actions-end .text=${t.delete} title=${t.delete ?? d} scale=s icon=trash @click=${(s) => {
      s.stopPropagation(), this.arcgisDeleteField.emit({ fieldName: e.name });
    }}></calcite-action>` : "";
  }
  renderAddButton() {
    return this.multiple ? l`<calcite-button .appearance=${this.hideCancel ? "outline-fill" : "solid"} .width=${this.hideCancel ? "full" : "half"} @click=${() => {
      this.arcgisClose.emit({ selectedFields: this.selectedFields }), this.arcgisFieldPickListDismissed.emit({ selectedFields: this.selectedFields });
    }}>${this.okBtnText || (this.multiple ? this._messages.done : this._messages.ok)}</calcite-button>` : "";
  }
  renderCancelButton() {
    return this.hideCancel ? "" : l`<calcite-button appearance=outline-fill .width=${this.multiple ? "half" : "full"} @click=${() => {
      this.arcgisClose.emit(), this.arcgisFieldPickListDismissed.emit();
    }}>${this._messages.cancel}</calcite-button>`;
  }
}
y("arcgis-field-pick-list", E);
export {
  E as ArcgisFieldPickList
};
