/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
import { c as b } from "../../chunks/runtime.js";
import { keyed as f } from "lit/directives/keyed.js";
import { B as c } from "../../chunks/common.js";
import "@arcgis/toolkit/type";
import { W as y } from "../../chunks/series-types.js";
import "@arcgis/toolkit/intl";
import { isEqual as C } from "lodash-es";
import "luxon";
import "d3-array";
import { ay as d, d4 as S, d3 as g } from "../../chunks/index.js";
import "@arcgis/core/Graphic.js";
import "@arcgis/core/renderers/support/jsonUtils.js";
import "@arcgis/core/symbols/support/symbolUtils.js";
import "@arcgis/core/intl.js";
import "@arcgis/core/layers/support/FeatureFilter.js";
import "@arcgis/core/smartMapping/statistics/histogram.js";
import "@arcgis/core/smartMapping/statistics/summaryStatistics.js";
import "simple-statistics";
import "@arcgis/core/request.js";
import "@arcgis/core/core/sql.js";
import "@arcgis/core/AttributeBinsGraphic.js";
import "@arcgis/core/geometry/support/jsonUtils.js";
import "@arcgis/core/rest/support/AttributeBinsQuery.js";
import "@arcgis/core/rest/support/StatisticDefinition.js";
import "@arcgis/core/time/TimeExtent.js";
import "@arcgis/core/core/promiseUtils.js";
import "@arcgis/toolkit/dom";
import { r as p } from "../../chunks/popover-ui-utils.js";
import { repeat as v } from "lit/directives/repeat.js";
import { a as l, c as m } from "../../chunks/interfaces.js";
import { d as $, s as F } from "../../chunks/store.js";
import { a as x } from "../../chunks/chart-ui-utils2.js";
import { u as I } from "../../chunks/useT9n.js";
import { css as B, nothing as P, html as a } from "lit";
import { createRef as h, ref as u } from "lit/directives/ref.js";
import { LitElement as O, createEvent as L, safeClassMap as o, renderElement as w } from "@arcgis/lumina";
import { x as E } from "../../chunks/data.js";
const r = {
  label: "label",
  fieldList: "field-list",
  fab: "fab",
  dimText: "dim-text",
  list: "list",
  customSortButtons: "custom-sort-buttons"
}, k = B`.hide{visibility:hidden}.am5-html-container{z-index:101!important}.am5-layer-1000{z-index:1000!important}.am5-layer-30{z-index:100!important}.show{display:block}.notifyPanel{flex:0 1 auto}.disable-interactions{pointer-events:none}.dim-text{color:var(--arcgis-charts-dim-text)}:host{display:flex;flex-direction:column;width:var(--arcgis-charts-config-calcite-block-default-width);margin:var(--arcgis-charts-config-calcite-block-default-margin);margin-top:var(--arcgis-charts-top-section-margin)}.label,.disabled-label{display:flex;margin-left:var(--arcgis-charts-config-margin-minor);margin-right:var(--arcgis-charts-config-margin-minor);margin-bottom:var(--arcgis-charts-config-margin-minor);justify-content:space-between}.field-list{max-height:50vh;overflow-y:auto}.disabled-label{pointer-events:none}.fab{display:flex;margin-left:var(--arcgis-charts-config-margin-minor);margin-right:var(--arcgis-charts-config-margin-minor);margin-bottom:1.5rem;justify-content:center}.list{margin-left:var(--arcgis-charts-config-margin-minor);margin-right:var(--arcgis-charts-config-margin-minor);margin-bottom:var(--arcgis-charts-config-margin-major)}.custom-sort-buttons{display:flex;justify-content:space-between;align-items:center;font-weight:var(--calcite-font-weight-medium);font-size:var(--calcite-font-size-0)}`;
class D extends O {
  constructor() {
    super(...arguments), this._messages = I(), this.boxPlotPopover = null, this.categoryElement = h(), this.numericFieldsElement = h(), this.splitByFieldElement = h(), this.sortOrderElement = h(), this.originalCustomSortLabels = [], this.isCustomSortDisabled = !1, this.onModelConfigChange = () => {
      this.requestUpdate();
    }, this.popoverClose = (t) => {
      this.boxPlotPopover === t?.target && (this.boxPlotPopover = p(this.boxPlotPopover));
    }, this.onBoxPlotDataChange = async (t) => {
      try {
        if (t.detail !== null && t.detail?.value !== void 0) {
          const { contentKind: e } = t.detail, s = [...t.detail.value];
          switch ($(F), e) {
            case l.category: {
              const i = s[0]?.trim() || d;
              if (this.model.category = i, this.model.getSortOrder() === c.customSort) {
                const n = await this.updateCustomSortProps();
                this.model.orderByList = n, this.sortOrderResetCounter += 1;
              }
              break;
            }
            case l.numericFields: {
              this.model.numericFields = s;
              const i = s.length > 1;
              if (this.model.standardizeValues = i, this.model.getSortOrder() === c.customSort) {
                const n = await this.updateCustomSortProps();
                this.model.orderByList = n, this.sortOrderResetCounter += 1;
              }
              break;
            }
            case l.splitByField: {
              const i = s[0]?.trim() || "";
              this.model.splitByField = i;
              break;
            }
            case l.sortOrder:
              {
                const i = s[0];
                if (i === c.customSort) {
                  const n = await this.updateCustomSortProps();
                  this.model.setSortOrder(i, n);
                } else
                  this.model.setSortOrder(i);
                this.sortOrderResetCounter += 1;
              }
              break;
            default:
              break;
          }
        }
      } catch (e) {
        throw e instanceof Error && this.arcgisChartsConfigDataChangeError.emit({ error: e, model: this.model }), e;
      }
      this.requestUpdate();
    }, this.selectedCustomSortItemId = "", this.sortOrderResetCounter = 0, this.layerFieldsInfo = [], this.arcgisChartsConfigDataChangeError = L();
  }
  static {
    this.properties = { selectedCustomSortItemId: 16, sortOrderResetCounter: 16, messageOverrides: 0, model: 0, layerFieldsInfo: 0 };
  }
  static {
    this.styles = k;
  }
  load() {
    this.modelChange(this.model), this.onModelConfigChange(), this.currentDataFilter = this.model.getDataFilters(), this.updateCustomSortProps();
  }
  willUpdate(t) {
    t.has("model") && this.modelChange(this.model, t.get("model")), C(this.model.getDataFilters(), this.currentDataFilter) || (this.updateCustomSortProps(), this.currentDataFilter = this.model.getDataFilters()), this.disableSplitBy = this.model.numericFields.length === 0 || this.model.numericFields.length > 1 && this.model.category !== d;
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this.boxPlotPopover = p(this.boxPlotPopover), this.model.removeEventListener("arcgisChartsModelConfigChange", this.onModelConfigChange);
  }
  modelChange(t, e) {
    e?.removeEventListener("arcgisChartsModelConfigChange", this.onModelConfigChange), t?.addEventListener("arcgisChartsModelConfigChange", this.onModelConfigChange);
  }
  onCalciteListOrderChange(t) {
    if (t.detail !== null && t.detail !== void 0) {
      const { newIndex: e, oldIndex: s } = t.detail;
      this.model.moveCustomSortValuesInOrderByList(s, e);
    }
  }
  onCustomSortItemSelected(t) {
    const { id: e } = t.target;
    this.selectedCustomSortItemId = this.selectedCustomSortItemId === e ? "" : e;
  }
  onCustomSortItemMoved(t) {
    const { id: e } = t.target;
    let s = this.model.orderByList.length;
    const i = this.model.orderByList.indexOf(this.selectedCustomSortItemId);
    e === m.Up ? s = i - 1 : e === m.Down && (s = i + 1), i >= 0 && s >= 0 && s < this.model.orderByList.length && (this.model.moveCustomSortValuesInOrderByList(i, s), this.sortOrderResetCounter += 1);
  }
  buildCustomSortListItems() {
    return v(this.model.orderByList, (e) => e, (e) => {
      const s = S(this.layerFieldsInfo, e);
      return a`<calcite-list-item id=${e ?? P} .label=${e ?? ""} .description=${s} .value=${e} .selected=${this.selectedCustomSortItemId === e} @calciteListItemSelect=${this.onCustomSortItemSelected}><calcite-icon slot=content-end></calcite-icon></calcite-list-item>`;
    });
  }
  buildCustomSortList() {
    return f(this.sortOrderResetCounter, a`<calcite-list label class=${o(r.list)} drag-enabled selection-mode=single selection-appearance=border @calciteListOrderChange=${this.onCalciteListOrderChange}>${this.buildCustomSortListItems()}</calcite-list>`);
  }
  buildNumericFieldItem(t) {
    return f(t, a`<calcite-list-item .label=${g(this.layerFieldsInfo, t)} .value=${t} closable @calciteListItemClose=${this.onRemoveNumericField}></calcite-list-item>`);
  }
  onCategorySelect(t) {
    this.categoryElement.value && !this.categoryElement.value.disabled && (this.contentKind = l.category, this.setupPopover(t));
  }
  async onRemoveNumericField(t) {
    const e = t.target.value;
    if (this.model.numericFields = this.model.numericFields.filter((s) => s !== e), this.model.numericFields.length === 0 && this.model.resetConfig(), this.model.getSortOrder() === c.customSort) {
      const s = await this.updateCustomSortProps();
      this.model.orderByList = s, this.sortOrderResetCounter += 1;
    }
  }
  async updateCustomSortProps() {
    const t = await this.model.getCustomSortValues();
    this.originalCustomSortLabels = [...t];
    const e = t.length > x.customSortLimit;
    return e && (this.sortOrderElement.value && (this.sortOrderElement.value.label = this._messages.xAxisAsc), this.model.setSortOrder(c.xAxisAsc)), this.isCustomSortDisabled = e, t;
  }
  onStandardizeValuesChange(t) {
    this.model.standardizeValues = t.target.checked;
  }
  onShowOutliersChange(t) {
    this.model.showOutliers = t.target.checked;
  }
  onSplitBySelect(t) {
    this.splitByFieldElement.value && !this.splitByFieldElement.value.disabled && (this.contentKind = l.splitByField, this.setupPopover(t));
  }
  onSortOrderSelect(t) {
    this.contentKind = l.sortOrder, this.setupPopover(t);
  }
  setupPopover(t) {
    t.stopImmediatePropagation(), this.boxPlotPopover = p(this.boxPlotPopover);
    let e, s, i, n = !1;
    switch (this.contentKind) {
      case l.category:
        e = this.categoryElement.value, s = this._messages.categoryHeader, i = this.model.category === d ? "" : this.model.category;
        break;
      case l.numericFields:
        e = this.numericFieldsElement.value, s = this._messages.numericFieldsHeader, i = this.model.numericFields;
        break;
      case l.splitByField:
        e = this.splitByFieldElement.value, s = this._messages.splitByFieldHeader, i = this.model.splitByField;
        break;
      case l.sortOrder:
        e = this.sortOrderElement.value, s = this._messages.selectSortOrder, i = this.model.getSortOrder(), n = this.isCustomSortDisabled;
        break;
    }
    this.boxPlotPopover = w(a`<arcgis-charts-config-box-plot-popover .headingTitle=${s} .referenceElement=${e} open .contentKind=${this.contentKind} .layerFieldsInfo=${this.layerFieldsInfo} .selectedContent=${i} .isCustomSortDisabled=${n} @arcgisChartsConfigBoxPlotDataPopoverChange=${this.onBoxPlotDataChange} @arcgisChartsConfigPopoverClose=${this.popoverClose}></arcgis-charts-config-box-plot-popover>`), !document.body.contains(this.boxPlotPopover) && this.boxPlotPopover !== null && document.body.appendChild(this.boxPlotPopover);
  }
  onAddNumericFields(t) {
    this.contentKind = l.numericFields, this.setupPopover(t);
  }
  getCorrectedSplitByValue() {
    return this.model.splitByField?.trim() === "" ? "" : g(this.layerFieldsInfo, this.model.splitByField);
  }
  getCorrectedCategoryValue() {
    return E({
      fieldName: this.model.category,
      fieldList: this.layerFieldsInfo
    }) ? "" : g(this.layerFieldsInfo, this.model.category);
  }
  resetToOriginalCustomSortLabels() {
    this.selectedCustomSortItemId = "", this.model.orderByList = [...this.originalCustomSortLabels], this.sortOrderResetCounter += 1;
  }
  renderCustomSortUI() {
    const t = this.model.getSortOrder(), e = this.model.getAxisValueFormat(0)?.type, s = this.model.orderByList.indexOf(this.selectedCustomSortItemId);
    return e === y.CategoryAxisFormat && t === c.customSort && !this.isCustomSortDisabled ? a`<calcite-label class=${o(r.label)}><div class=${o(r.customSortButtons)}><div><calcite-button appearance=transparent .disabled=${s === 0 || s === -1 || this.selectedCustomSortItemId.trim() === ""} icon-start=arrow-bold-up id=${m.Up} kind=neutral scale=s @click=${this.onCustomSortItemMoved}></calcite-button><calcite-button appearance=transparent .disabled=${s === -1 || s === this.model.orderByList.length - 1 || this.selectedCustomSortItemId.trim() === ""} icon-start=arrow-bold-down id=${m.Down} kind=neutral scale=s @click=${this.onCustomSortItemMoved}></calcite-button></div><calcite-button @click=${this.resetToOriginalCustomSortLabels} .disabled=${C(this.model.orderByList, this.originalCustomSortLabels)} appearance=transparent icon-end=reset>${this._messages.reset}</calcite-button></div>${this.model.category === d ? this._messages.values : this._messages.category}${this.buildCustomSortList()}</calcite-label>` : null;
  }
  renderNumericFields(t) {
    const e = [];
    for (const s of t)
      e.push(this.buildNumericFieldItem(s));
    return a`<calcite-list label class=${o(r.fieldList)} ${u(this.numericFieldsElement)}>${e}</calcite-list>`;
  }
  renderCategory() {
    const t = this.getCorrectedCategoryValue(), e = this.model.numericFields.length === 0 || (this.model.numericFields ?? []).length > 1 && this.model.splitByField !== "";
    return a`<arcgis-charts-config-field-select .label=${t} .disabled=${e} @click=${this.onCategorySelect} ${u(this.categoryElement)}></arcgis-charts-config-field-select>`;
  }
  renderSplitBy() {
    const t = this.getCorrectedSplitByValue();
    return a`<arcgis-charts-config-field-select .label=${t} .disabled=${this.disableSplitBy} @click=${this.onSplitBySelect} ${u(this.splitByFieldElement)}></arcgis-charts-config-field-select>`;
  }
  renderSorting() {
    return a`<arcgis-charts-config-field-select .label=${this._messages[this.model.getSortOrder()]} @click=${this.onSortOrderSelect} ${u(this.sortOrderElement)}></arcgis-charts-config-field-select>`;
  }
  render() {
    const t = this.renderCategory(), e = this.renderNumericFields([...this.model.numericFields ?? []]), s = this.renderSplitBy(), i = this.renderSorting(), n = this.renderCustomSortUI();
    return a`<calcite-label class=${o(r.label)}>${this._messages.numericFields}${e}</calcite-label><div class=${o(r.fab)}><calcite-fab appearance=outline-fill kind=neutral scale=m .label=${this._messages.selectNumericFields} text-enabled .text=${this._messages.selectNumericFields} icon=plus @click=${this.onAddNumericFields}></calcite-fab></div><calcite-label class=${o(r.label)}><div>${this._messages.category} <span class=${o(r.dimText)}>(${this._messages.optional})</span></div>${t}</calcite-label><calcite-label class=${o(r.label)}><div class=${o(this.disableSplitBy ? r.dimText : "")}>${this._messages.splitBy} <span class=${o(r.dimText)}>(${this._messages.optional})</span></div>${s}</calcite-label><div>${(this.model.numericFields ?? []).length > 1 ? a`<calcite-label class=${o(r.label)} layout=inline-space-between>${this._messages.standardizeValues}<calcite-switch .checked=${this.model.standardizeValues} @calciteSwitchChange=${this.onStandardizeValuesChange}></calcite-switch></calcite-label>` : null}</div><calcite-label class=${o(r.label)} layout=inline-space-between>${this._messages.showOutliers}<calcite-switch .checked=${this.model.showOutliers} @calciteSwitchChange=${this.onShowOutliersChange}></calcite-switch></calcite-label><calcite-label class=${o(r.label)}>${this._messages.sortOrder}${i}</calcite-label>${n}`;
  }
}
b("arcgis-charts-config-box-plot-data", D);
export {
  D as ArcgisChartsConfigBoxPlotData
};
