/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
import { c as w } from "../../chunks/runtime.js";
import { keyed as $ } from "lit/directives/keyed.js";
import "@arcgis/toolkit/intl";
import { isEqual as f } from "lodash-es";
import "luxon";
import "d3-array";
import { bR as I, by as k, bz as O, b as D, d3 as y, d4 as E, ds as P, o as F, dp as B, bT as _, da as N } from "../../chunks/index.js";
import { a as g, i as A, W as p, m as b } from "../../chunks/series-types.js";
import "@arcgis/toolkit/type";
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/core/request.js";
import "@arcgis/toolkit/dom";
import "@arcgis/core/intl.js";
import { r as U } from "../../chunks/popover-ui-utils.js";
import { S as d } from "../../chunks/common.js";
import { repeat as V } from "lit/directives/repeat.js";
import { B as a, c as C } from "../../chunks/interfaces.js";
import { d as z, s as S, r as M, a as R } from "../../chunks/store.js";
import { a as K } from "../../chunks/chart-ui-utils2.js";
import { u as L } from "../../chunks/useT9n.js";
import { css as j, html as n, nothing as H } from "lit";
import { createRef as c, ref as m } from "lit/directives/ref.js";
import { LitElement as W, createEvent as v, safeClassMap as l, renderElement as q } from "@arcgis/lumina";
import { x as Z } from "../../chunks/data.js";
const r = {
  label: "label",
  fieldList: "field-list",
  fab: "fab",
  disabledLabel: "disabled-label",
  timeBinningHeader: "time-binning-header",
  linkContainer: "link-container",
  list: "list",
  customSortButtons: "custom-sort-buttons",
  dimText: "dim-text",
  intervalContainer: "interval-container"
}, G = j`.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}.time-binning-header{display:flex;font-weight:700;margin-left:.5rem;margin-right:.5rem;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}.link-container{display:flex;justify-content:flex-end}.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)}.mb-2{margin-bottom:var(--arcgis-charts-config-margin-minor)}.interval-container{margin-left:var(--arcgis-charts-config-margin-minor);margin-right:var(--arcgis-charts-config-margin-minor);margin-bottom:var(--arcgis-charts-config-margin-minor)}`;
class J extends W {
  constructor() {
    super(...arguments), this._messages = L(), this.commonStrings = L({ name: "common", blocking: !0 }), this.barChartPopover = null, this.sortOrderElement = c(), this.aggregationElement = c(), this.categoryElement = c(), this.numericFieldsElement = c(), this.splitByFieldElement = c(), this.enableTimeBinningSwitch = c(), this.intervalAlignmentElement = c(), this.intervalElement = c(), this.originalCustomSortLabels = [], this.isCustomSortDisabled = !1, this.onBarChartDataChange = async (e) => {
      try {
        if (e.detail !== null && e.detail?.value !== void 0) {
          const { contentKind: t } = e.detail, i = [...e.detail.value];
          switch (z(S), t) {
            case a.aggregation:
              this.model.aggregationType = i[0] !== g.NoAggregation ? i[0] : g.NoAggregation;
              break;
            case a.category: {
              const s = i[0]?.trim() || "";
              if (this.model.xAxisField = s, this.model.getSortOrder() === d.customSort) {
                const o = await this.updateCustomSortProps();
                this.model.orderByList = o, this.sortOrderResetCounter += 1;
              }
              break;
            }
            case a.numericFields:
              if (this.model.numericFields = i, (this.model.numericFields ?? []).length > 0 && this.model.aggregationType === g.Count && this.model.numericFields[0] !== I(this.model.layer).idField && (this.model.aggregationType = g.Sum), this.model.getSortOrder() === d.customSort) {
                const s = await this.updateCustomSortProps();
                this.model.orderByList = s, this.sortOrderResetCounter += 1;
              }
              break;
            case a.splitByField: {
              const s = i[0]?.trim() || "";
              this.model.splitByField = s, this.model.colorMatch = !0;
              break;
            }
            case a.sortOrder: {
              const s = i[0];
              if (s === d.customSort) {
                const o = await this.updateCustomSortProps();
                this.model.setSortOrder(s, o);
              } else
                this.model.setSortOrder(s);
              this.sortOrderResetCounter += 1;
              break;
            }
            case a.interval:
              this.model.temporalBinningSize = i[0]?.intervalSize, this.model.temporalBinningUnit = i[0]?.intervalUnits, this.arcgisChartsConfigCustomizedTimeInterval.emit();
              break;
            case a.intervalAlignment:
              this.model.timeAggregationType = i[0] ?? "";
              break;
            default:
              break;
          }
          t !== a.interval && t !== a.intervalAlignment && M(S);
        }
      } catch (t) {
        throw this.arcgisChartsConfigDataChangeError.emit({ error: t, model: this.model }), t;
      }
      this.removeBarChartDataPopover(), this.requestUpdate();
    }, this.onModelConfigChange = () => {
      this.requestUpdate();
    }, this.popoverClose = (e) => {
      this.barChartPopover === e?.target && this.removeBarChartDataPopover();
    }, this.selectedCustomSortItemId = "", this.sortOrderResetCounter = 0, this.layerFieldsInfo = [], this.arcgisChartsConfigBarChartDataNumericFieldValidate = v(), this.arcgisChartsConfigDataChangeError = v(), this.arcgisChartsConfigResetTimeInterval = v(), this.arcgisChartsConfigCustomizedTimeInterval = v();
  }
  static {
    this.properties = { selectedCustomSortItemId: 16, aggregationLabel: 16, timeAggregationLabel: 16, disableSplitBy: 16, sortOrderResetCounter: 16, messageOverrides: 0, model: 0, layerFieldsInfo: 0, open: 5 };
  }
  static {
    this.styles = G;
  }
  load() {
    this.modelChange(this.model), this.onModelConfigChange(), this.currentDataFilter = this.model.getDataFilters(), this.updateCustomSortProps();
  }
  willUpdate(e) {
    e.has("model") && this.modelChange(this.model, e.get("model")), this.aggregationLabel = k(this.model.aggregationType, this.commonStrings), f(this.model.getDataFilters(), this.currentDataFilter) || (this.model.getSortOrder() === d.customSort && this.updateCustomSortProps(), this.currentDataFilter = this.model.getDataFilters());
    const t = this.model.timeAggregationType;
    t !== void 0 && (this.timeAggregationLabel = O(t, this.commonStrings)), this.disableSplitBy = this.model.numericFields.length > 1 || this.model.xAxisField === "" || this.model.xAxisField === D;
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this.removeBarChartDataPopover(), this.model.removeEventListener("arcgisChartsModelConfigChange", this.onModelConfigChange);
  }
  modelChange(e, t) {
    t?.removeEventListener("arcgisChartsModelConfigChange", this.onModelConfigChange), e?.addEventListener("arcgisChartsModelConfigChange", this.onModelConfigChange);
  }
  onCalciteListOrderChange(e) {
    if (e.detail !== null && e.detail !== void 0) {
      const { newIndex: t, oldIndex: i } = e.detail;
      this.model.moveCustomSortValuesInOrderByList(i, t);
    }
  }
  onCustomSortItemSelected(e) {
    const { id: t } = e.target;
    this.selectedCustomSortItemId = this.selectedCustomSortItemId === t ? "" : t;
  }
  onCustomSortItemMoved(e) {
    const { id: t } = e.target;
    let i = this.model.orderByList.length;
    const s = this.model.orderByList.indexOf(this.selectedCustomSortItemId);
    t === C.Up ? i = s - 1 : t === C.Down && (i = s + 1), s >= 0 && i >= 0 && i < this.model.orderByList.length && (this.model.moveCustomSortValuesInOrderByList(s, i), this.sortOrderResetCounter += 1);
  }
  onEnableTimeBinningChange(e) {
    const t = e.target.checked;
    this.model.binTemporalData = t, this.requestUpdate();
  }
  buildNumericFieldItem(e) {
    return $(e, n`<calcite-list-item .label=${y(this.layerFieldsInfo, e)} .value=${e} closable @calciteListItemClose=${this.onRemoveNumericField}></calcite-list-item>`);
  }
  resetTimeIntervalOriginal(e) {
    this.popoverClose(e), this.model.resetTimeInterval !== void 0 && (this.model.resetTimeInterval(), this.arcgisChartsConfigResetTimeInterval.emit());
  }
  buildCustomSortListItems() {
    return V(this.model.orderByList, (t) => t, (t) => {
      const i = E(this.layerFieldsInfo, t), o = this.model.nullCategory !== void 0 && t.trim() === P.nullCategory?.text?.trim();
      return n`<calcite-list-item id=${t ?? H} .label=${t} .closed=${o} .description=${i} .value=${t} .selected=${this.selectedCustomSortItemId === t} @calciteListItemSelect=${this.onCustomSortItemSelected}><calcite-icon slot=content-end></calcite-icon></calcite-list-item>`;
    });
  }
  buildCustomSortList() {
    return $(this.sortOrderResetCounter, n`<calcite-list label class=${l(r.list)} drag-enabled selection-mode=single selection-appearance=border @calciteListOrderChange=${this.onCalciteListOrderChange}>${this.buildCustomSortListItems()}</calcite-list>`);
  }
  onAggregationSelect(e) {
    this.contentKind = a.aggregation, this.setupPopover(e);
  }
  onSortOrderSelect(e) {
    this.contentKind = a.sortOrder, this.setupPopover(e);
  }
  onCategorySelect(e) {
    this.contentKind = a.category, this.setupPopover(e);
  }
  onSplitBySelect(e) {
    this.splitByFieldElement.value && !this.splitByFieldElement.value.disabled && (this.contentKind = a.splitByField, this.setupPopover(e));
  }
  onAddNumericFields(e) {
    this.contentKind = a.numericFields, this.setupPopover(e);
  }
  async onRemoveNumericField(e) {
    const t = e.target.value;
    if (this.model.numericFields = this.model.numericFields.filter((i) => i !== t), this.model.getSortOrder() === d.customSort) {
      const i = await this.updateCustomSortProps();
      this.model.orderByList = i, this.sortOrderResetCounter += 1;
    }
  }
  onIntervalAlignmentSelect(e) {
    this.intervalAlignmentElement.value && !this.intervalAlignmentElement.value.disabled && (this.contentKind = a.intervalAlignment, this.setupPopover(e));
  }
  onIntervalSelect(e) {
    this.intervalElement.value && !this.intervalElement.value.disabled && (this.contentKind = a.interval, this.setupPopover(e));
  }
  getCorrectedSplitByValue() {
    return this.model.splitByField === "" || (this.model.numericFields ?? []).length > 1 ? "" : y(this.layerFieldsInfo, this.model.splitByField);
  }
  getCorrectedCategoryValue() {
    return Z({
      fieldName: this.model.xAxisField,
      fieldList: this.layerFieldsInfo
    }) ? "" : y(this.layerFieldsInfo, this.model.xAxisField);
  }
  onShowDataLabelsChange(e) {
    this.model.dataLabelsVisibility = e.target.checked;
  }
  onTreatNullAsCategoryChange(e) {
    this.model.fetchNULLValues = e.target.checked;
  }
  async updateCustomSortProps() {
    const e = await this.model.getCustomSortValues();
    this.originalCustomSortLabels = [...e];
    const t = e.length > K.customSortLimit;
    return t && (this.sortOrderElement.value && (this.sortOrderElement.value.label = this._messages.xAxisAsc), this.model.setSortOrder(d.xAxisAsc)), this.isCustomSortDisabled = t, e;
  }
  setupPopover(e) {
    e.stopImmediatePropagation(), this.removeBarChartDataPopover();
    const t = {
      size: this.model.temporalBinningSize ?? 1,
      unit: this.model.temporalBinningUnit ?? A.Second
    };
    let i, s, o, h = !1, u = !1;
    switch (this.contentKind) {
      case a.aggregation:
        i = this.aggregationElement.value, s = this._messages.aggregationHeader, h = F(this.model.config.series ?? []) === B.BarAndLineFromFields, o = this.model.aggregationType;
        break;
      case a.category:
        i = this.categoryElement.value, s = this._messages.categoryHeader, o = this.model.xAxisField;
        break;
      case a.numericFields:
        i = this.numericFieldsElement.value, s = this._messages.numericFieldsHeader, o = this.model.numericFields;
        break;
      case a.splitByField:
        i = this.splitByFieldElement.value, s = this._messages.splitByFieldHeader, o = this.model.splitByField;
        break;
      case a.sortOrder:
        i = this.sortOrderElement.value, s = this._messages.sortOrderHeader, o = this.model.getSortOrder(), u = this.isCustomSortDisabled;
        break;
      case a.interval:
        i = this.intervalElement.value, s = this._messages.editInterval, o = t;
        break;
      case a.intervalAlignment:
        i = this.intervalAlignmentElement.value, s = this._messages.intervalAlignment, o = this.model.timeAggregationType ?? "";
        break;
    }
    this.barChartPopover = q(n`<arcgis-charts-config-bar-chart-popover .headingTitle=${s} .referenceElement=${i} open .contentKind=${this.contentKind} .layerFieldsInfo=${this.layerFieldsInfo} .selectedContent=${o} .isCustomSortDisabled=${u} .isNoAggregationDisabled=${h} @arcgisChartsConfigBarChartDataPopoverChange=${this.onBarChartDataChange} @arcgisChartsConfigPopoverClose=${this.popoverClose}></arcgis-charts-config-bar-chart-popover>`), !document.body.contains(this.barChartPopover) && this.barChartPopover !== null && document.body.appendChild(this.barChartPopover);
  }
  removeBarChartDataPopover() {
    this.barChartPopover !== null && (this.barChartPopover.open = !1, this.barChartPopover = U(this.barChartPopover));
  }
  resetToOriginalCustomSortLabels() {
    this.selectedCustomSortItemId = "", this.model.orderByList = [...this.originalCustomSortLabels], this.sortOrderResetCounter += 1;
  }
  onTrimIncompleteIntervalChange(e) {
    this.model.trimIncompleteTimeInterval = e.target.checked;
  }
  onNullPolicyChange(e) {
    this.model.nullPolicy = e.target.selectedItem.value;
  }
  shouldShowTimeBinning() {
    const e = this.layerFieldsInfo.find((i) => i.name === this.model.xAxisField), t = this.model.aggregationType !== g.NoAggregation;
    return e !== void 0 && _(e) && t;
  }
  renderSorting() {
    return n`<arcgis-charts-config-field-select .disabled=${this.model.getAxisValueFormat(0)?.type === p.DateAxisFormat} .label=${this.model.getAxisValueFormat(0)?.type === p.DateAxisFormat ? this._messages.xAxisAsc : this._messages[this.model.getSortOrder()]} @click=${this.onSortOrderSelect} ${m(this.sortOrderElement)}></arcgis-charts-config-field-select>`;
  }
  renderAggregation() {
    return n`<arcgis-charts-config-field-select .label=${this.model.aggregationType === g.NoAggregation ? this._messages.noAggregation : this.aggregationLabel} @click=${this.onAggregationSelect} ${m(this.aggregationElement)}></arcgis-charts-config-field-select>`;
  }
  renderCategory() {
    const e = this.getCorrectedCategoryValue();
    return n`<arcgis-charts-config-field-select .label=${e} @click=${this.onCategorySelect} ${m(this.categoryElement)}></arcgis-charts-config-field-select>`;
  }
  renderSplitBy() {
    const e = this.getCorrectedSplitByValue();
    return n`<arcgis-charts-config-field-select .label=${e} .disabled=${this.disableSplitBy} @click=${this.onSplitBySelect} ${m(this.splitByFieldElement)}></arcgis-charts-config-field-select>`;
  }
  renderNumericFields(e) {
    const t = I(this.model.layer).idField, i = [];
    for (const s of e)
      s !== t && i.push(this.buildNumericFieldItem(s));
    return n`<calcite-list label class=${l(r.fieldList)} ${m(this.numericFieldsElement)}>${i}</calcite-list>`;
  }
  renderCustomSortUI() {
    const e = this.model.getSortOrder(), t = this.model.getAxisValueFormat(0)?.type, i = this.model.orderByList.indexOf(this.selectedCustomSortItemId);
    return t === p.CategoryAxisFormat && e === d.customSort && !this.isCustomSortDisabled ? n`<calcite-label class=${l(r.label)}><div class=${l(r.customSortButtons)}><div><calcite-button appearance=transparent .disabled=${i === 0 || i === -1 || this.selectedCustomSortItemId.trim() === ""} icon-start=arrow-bold-up id=${C.Up} kind=neutral scale=s @click=${this.onCustomSortItemMoved}></calcite-button><calcite-button appearance=transparent .disabled=${i === -1 || i === this.model.orderByList.length - 1 || this.selectedCustomSortItemId.trim() === ""} icon-start=arrow-bold-down id=${C.Down} kind=neutral scale=s @click=${this.onCustomSortItemMoved}></calcite-button></div><calcite-button @click=${this.resetToOriginalCustomSortLabels} .disabled=${f(this.model.orderByList, this.originalCustomSortLabels)} appearance=transparent icon-end=reset>${this._messages.reset}</calcite-button></div>${F(this.model.config.series ?? []) === B.BarAndLineFromFields ? this._messages.values : this._messages.category}${this.buildCustomSortList()}</calcite-label>` : null;
  }
  renderInterval() {
    const e = (this.model.temporalBinningSize ?? 0) <= 0, t = this.model.temporalBinningSize ?? "", i = N(this.model.temporalBinningUnit ?? A.Second, this._messages) ?? "", s = R(S), o = {
      size: this.model.temporalBinningSize,
      unit: this.model.temporalBinningUnit
    }, h = f(o, s);
    return [
      n`<calcite-list label selection-appearance=border class=${l(r.intervalContainer)}><calcite-list-item .value=${e ? "" : `${t} ${i}`} .label=${e ? "" : `${t} ${i}`} @click=${e ? () => {
      } : this.onIntervalSelect} ${m(this.intervalElement)}><calcite-icon slot=content-end icon=pencil></calcite-icon></calcite-list-item></calcite-list>`,
      n`<div class=${l(r.linkContainer)}><calcite-button .disabled=${h} appearance=transparent scale=s icon-end=reset @click=${this.resetTimeIntervalOriginal}>${this._messages.reset}</calcite-button></div>`
    ];
  }
  renderIntervalAlignment() {
    return n`<arcgis-charts-config-field-select .label=${this.timeAggregationLabel} @click=${this.onIntervalAlignmentSelect} ${m(this.intervalAlignmentElement)}></arcgis-charts-config-field-select>`;
  }
  renderEmptyBins() {
    return n`<calcite-radio-button-group name=empty-bins layout=vertical @calciteRadioButtonGroupChange=${this.onNullPolicyChange}><calcite-label layout=inline><calcite-radio-button .value=${b.Zero} .checked=${this.model.nullPolicy === b.Zero}></calcite-radio-button>${this._messages.treatAsZero}</calcite-label><calcite-label layout=inline><calcite-radio-button .value=${b.Null} .checked=${this.model.nullPolicy === b.Null}></calcite-radio-button>${this._messages.treatAsNull}</calcite-label></calcite-radio-button-group>`;
  }
  render() {
    const e = this.renderAggregation(), t = this.renderCategory(), i = this.renderSplitBy(), s = this.renderSorting(), o = this.renderNumericFields([...this.model.numericFields ?? []]), h = this.renderCustomSortUI(), u = this.renderInterval(), x = this.renderIntervalAlignment(), T = this.renderEmptyBins();
    return n`<calcite-label class=${l(r.label)}>${this._messages.category}${t}</calcite-label><calcite-label class=${l(r.label)}>${this._messages.aggregation}${e}</calcite-label><calcite-label class=${l(r.label)}>${this._messages.numericFields}${o}</calcite-label><div class=${l(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=${l(r.label)}><span class=${l(this.disableSplitBy ? r.dimText : "")}>${this._messages.splitBy}</span>${i}</calcite-label><div .hidden=${!this.shouldShowTimeBinning()}><h3 class=${l(r.timeBinningHeader)}>${this._messages.timeBinningOptions}</h3><calcite-label class=${l(r.label)} layout=inline-space-between>${this._messages.enableTemporalBinning}<calcite-switch .checked=${this.model.binTemporalData} @calciteSwitchChange=${this.onEnableTimeBinningChange} ${m(this.enableTimeBinningSwitch)}></calcite-switch></calcite-label><div .hidden=${!this.model.binTemporalData || !this.shouldShowTimeBinning()}><calcite-label class=${l(r.label)}>${this._messages.interval}${u}</calcite-label><calcite-label class=${l(r.label)}>${this._messages.intervalAlignment}${x}</calcite-label><calcite-label class=${l(r.label)} layout=inline-space-between>${this._messages.trimIncompleteInterval}<calcite-switch .checked=${this.model.trimIncompleteTimeInterval} @calciteSwitchChange=${this.onTrimIncompleteIntervalChange}></calcite-switch></calcite-label><calcite-label class=${l(r.label)}>${this._messages.emptyBins}${T}</calcite-label></div></div><calcite-label class=${l(r.label)} layout=inline-space-between>${this._messages.treatNullAsCategory}<calcite-switch .checked=${this.model.fetchNULLValues} @calciteSwitchChange=${this.onTreatNullAsCategoryChange}></calcite-switch></calcite-label><calcite-label class=${l(r.label)} layout=inline-space-between>${this._messages.showDataLabels}<calcite-switch .checked=${this.model.dataLabelsVisibility} @calciteSwitchChange=${this.onShowDataLabelsChange}></calcite-switch></calcite-label><calcite-label class=${l(this.model.getAxisValueFormat(0)?.type === p.DateAxisFormat ? r.disabledLabel : r.label)}>${this._messages.sortOrder}${s}</calcite-label>${h}`;
  }
}
w("arcgis-charts-config-bar-chart-data", J);
export {
  J as ArcgisChartsConfigBarChartData
};
