/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { c } from "../../chunks/runtime.js";
import { ref as d } from "lit/directives/ref.js";
import { css as h, html as i } from "lit";
import { LitElement as f, createEvent as l } from "@arcgis/lumina";
import { focusElement as m, getClosestElement as u } from "@arcgis/toolkit/dom";
import { createFilterExpression as g } from "@arcgis/toolkit/string";
import { u as b } from "../../chunks/useT9n.js";
import { log as p } from "@arcgis/toolkit/log";
import { g as o, h as n, j as _, k as v } from "../../chunks/utils.js";
const w = h`:host{background-color:var(--calcite-color-foreground-1);.notice-container{margin:var(--calcite-spacing-xxs);padding:var(--calcite-spacing-sm);background-color:var(--calcite-color-foreground-1)}.sticky{position:sticky;top:0;z-index:10}calcite-flow{height:100%}calcite-list-item-group{background-color:var(--calcite-color-foreground-2);word-break:break-word}}`;
function $(a) {
  a.key === "Enter" && a.stopPropagation();
}
class C extends f {
  constructor() {
    super(...arguments), this._beforeBack = async () => {
      this.removeLastPanelRenderer(), this._filterValue = "";
    }, this.messages = b(), this._filterValue = "", this._flowItemRenderers = [], this._rootPresentation = "profile", this._mutationCounter = 1, this.loading = !1, this.closed = !1, this.arcgisInternalClosePanel = l({ bubbles: !1, composed: !1 }), this.arcgisInternalItemSelected = l({ bubbles: !1 });
  }
  static {
    this.properties = { _filterValue: 16, _flowItemRenderers: 16, _rootPresentation: 16, _mutationCounter: 16, loading: 5, modelId: 1, closed: 5, variable: 0, heading: 1, messageOverrides: 0 };
  }
  static {
    this.styles = w;
  }
  load() {
    this._variableChanged();
  }
  willUpdate(e) {
    e.has("modelId") && (this._flowItemRenderers = []), e.has("variable") && this._variableChanged();
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this._flowObserver?.disconnect();
  }
  _variableChanged() {
    if (!this.variable || o(this.variable)) {
      this._rootPresentation = "profile";
      return;
    }
    this._rootPresentation = this.variable.type === "featureSet" ? "featureSetRoot" : "collectionRoot";
  }
  addPanelRenderer(e) {
    this._flowItemRenderers = [...this._flowItemRenderers, e];
  }
  removeLastPanelRenderer() {
    this._flowItemRenderers = this._flowItemRenderers.slice(0, -1);
  }
  _isRootPresentation(e) {
    return this._rootPresentation === e;
  }
  flowFocusHandler(e) {
    if (!e) {
      this._flowObserver?.disconnect(), this._flowObserver = void 0;
      return;
    }
    this._flowObserver || (this._flowObserver = new MutationObserver(() => {
      m(u(e.querySelector("calcite-flow-item:last-child") ?? e, "calcite-input"));
    }), this._flowObserver.observe(e, { attributes: !0, attributeFilter: ["id"], childList: !0 }));
  }
  _updateFilterValue(e) {
    this._filterValue = e.currentTarget.value;
  }
  _emitClose() {
    this.arcgisInternalClosePanel.emit();
  }
  _backToTop() {
    this._flowItemRenderers = [];
  }
  _emitItemSelected(e, t) {
    if (t.nonInteractive)
      return;
    const s = e;
    (!s.key || s.key === "Enter") && (e.preventDefault(), this.arcgisInternalItemSelected.emit(t.snippet));
  }
  _showCollectionPanel(e, t) {
    e.stopPropagation(), this.addPanelRenderer(
      // Add a function to render the variable
      (s) => this.renderCollectionBasedVariable(t, !1, s)
    );
  }
  _getHeadingForCollection(e, t = !1) {
    if (!e)
      return "";
    if (t) {
      if (this.heading)
        return this.heading;
      if (o(this.variable))
        return this.variable.definition?.label ?? this.messages.profilevariables ?? "Profile variables";
      if (this._isRootPresentation("featureSetRoot"))
        return this.messages.fields ?? "Fields";
      if (this._isRootPresentation("collectionRoot"))
        return this.messages.tables ?? "Tables";
    }
    return n(e) || _(e) ? this.messages.fields ?? "Fields" : this.messages.profilevariables ?? "Profile variables";
  }
  _getDescriptionForCollection(e) {
    return e ? n(e) ? e.variables[0]?.getLabel() ?? "" : v(e) ? e.datastoreInfo?.name ?? e.getDescription() ?? "" : e.breadcrumb : "";
  }
  renderCollectionBasedVariable(e, t = !1, s = !1) {
    if (!e)
      return null;
    let r = this.loading;
    return !r && !e.loaded && (e.loadSource().then(() => setTimeout(() => {
      this._mutationCounter += 1;
    })).catch(() => {
      p("error", this, "Error loading collection"), r = !1;
    }), r = !0), i`<calcite-flow-item heading-level=2 .heading=${this._getHeadingForCollection(e, t)} .description=${this._getDescriptionForCollection(e)} .beforeBack=${this._beforeBack} closable @calciteFlowItemClose=${this._emitClose} .selected=${s}><calcite-action slot=header-actions-end .text=${this.messages.backtotop ?? ""} scale=m .hidden=${t || this._isRootPresentation("featureSetRoot")} icon=chevrons-left icon-flip-rtl @click=${this._backToTop}></calcite-action><calcite-input .value=${this._filterValue} icon=magnifying-glass clearable @calciteInputInput=${this._updateFilterValue} class="sticky" scale=m .label=${this.messages.filterthevariablesbyname ?? ""} name=variable-filter></calcite-input>${r ? i`<calcite-loader scale=s type=indeterminate .label=${this.messages.loading ?? ""}></calcite-loader>` : i`<calcite-list .label=${this.messages.profilevariables ?? "Profile variables"}>${this.renderEditorVariables(e)}</calcite-list>`}</calcite-flow-item>`;
  }
  renderEditorVariables(e) {
    const t = g(this._filterValue), s = e.variables.filter((r) => r.passFilter(t));
    return s.length ? s.map((r) => this.renderEditorVariable(r)) : i`<div class="notice-container">${this.messages.noitems}</div>`;
  }
  renderEditorVariable(e) {
    switch (e.type) {
      case "group":
        return this._isRootPresentation("featureSetRoot") && e.isHeader ? i`<calcite-list-item-group .heading=${e.getLabel()}></calcite-list-item-group>` : this._isRootPresentation("featureSetRoot") && e._label?.code === "fields" ? this.renderEditorVariables(e) : i`<calcite-list-item-group .heading=${e.getLabel()}>${this.renderEditorVariables(e)}</calcite-list-item-group>`;
      default:
        return i`<calcite-list-item .label=${e.getLabel()} .description=${e.getDescription()} @calciteListItemSelect=${(t) => this._emitItemSelected(t, e)} @keydown=${(t) => this._emitItemSelected(t, e)}>${e.isCollection ? i`<calcite-action slot=actions-end .text=${this.messages.expand ?? ""} scale=s icon=chevron-right icon-flip-rtl @click=${(t) => this._showCollectionPanel(t, e)} @keydown=${$}></calcite-action>` : null}${e.icon ? i`<calcite-icon .icon=${e.icon} scale=s slot=content-start></calcite-icon>` : null}</calcite-list-item>`;
    }
  }
  render() {
    return this.closed ? null : this.loading && !this.variable ? i`<calcite-flow><calcite-flow-item heading-level=2 .heading=${this.heading ?? this.messages.profilevariables} closable @calciteFlowItemClose=${this._emitClose}><calcite-loader scale=s type=indeterminate .label=${this.messages.loading ?? ""}></calcite-loader></calcite-flow-item></calcite-flow>` : !this.loading && (!this.variable || this.variable?.loaded && !this.variable?.variables.length) ? i`<calcite-flow><calcite-flow-item heading-level=2 .heading=${this.heading ?? this.messages.profilevariables} closable @calciteFlowItemClose=${this._emitClose}><div class="notice-container">${this.messages.profileempty}</div></calcite-flow-item></calcite-flow>` : i`<calcite-flow ${d(this.flowFocusHandler)}>${this.renderCollectionBasedVariable(this.variable, !0, this._flowItemRenderers.length === 0)}${this._flowItemRenderers.map((e, t, s) => (
      // check if the current flow item is the last one, if so, renderer will set selected = true
      e(t === s.length - 1)
    ))}</calcite-flow>`;
  }
}
c("arcgis-editor-variables", C);
export {
  C as ArcgisEditorVariables
};
