/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
import { c as D } from "../../chunks/runtime.js";
import { LitElement as E, createEvent as M, renderElement as P, safeClassMap as n, safeStyleMap as F } from "@arcgis/lumina";
import { getElementLocale as I, normalizeLocale as w, defaultLocale as _ } from "@arcgis/toolkit/intl";
import { css as O, html as r } from "lit";
import { createRef as d, ref as p } from "lit/directives/ref.js";
import { isEqual as B, cloneDeep as H, parseInt as L, camelCase as N } from "lodash-es";
import { DateTime as U } from "luxon";
import { bR as W, _ as V, by as K, ds as x, az as q, d3 as R, de as z, aA as f } from "../../chunks/index.js";
import { u as T } from "../../chunks/useT9n.js";
import { d as l, W as v } from "../../chunks/interfaces.js";
import { H as j } from "../../chunks/common.js";
import "@arcgis/toolkit/type";
import { j as y, W as h, a as u, m as g, v as b, l as k, u as X } from "../../chunks/series-types.js";
import { f as Z } from "../../chunks/rest-js-object-literals.js";
import { x as Y } from "../../chunks/data.js";
import { i as G } from "../../chunks/utils.js";
import "d3-array";
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 J } from "../../chunks/popover-ui-utils.js";
import { j as $, s as Q } from "../../chunks/chart-ui-utils2.js";
import { c as A, g as ee, a as te, b as ae, p as se, d as le, i as ie } from "../../chunks/class-breaks.js";
import { c as oe, s as re } from "../../chunks/store.js";
const ne = O`.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{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}.color-ramp{width:100%;height:20px;overflow:hidden;border-radius:0}.color-ramp-segment{height:100%;display:inline-block}.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)}.accordion{margin-top:var(--arcgis-charts-config-margin-minor);margin-bottom:var(--arcgis-charts-config-margin-major)}`, c = {
  label: "label",
  colorRamp: "color-ramp",
  colorRampSegment: "color-ramp-segment",
  list: "list",
  accordion: "accordion"
};
class ce extends E {
  constructor() {
    super(...arguments), this._messages = T(), this.commonStrings = T({ name: "common", blocking: !0 }), this.heatChartPopover = null, this.xAxisFieldElement = d(), this.aggregationElement = d(), this.numericFieldsElement = d(), this.calendarTypeElement = d(), this.calendarViewTypeElement = d(), this.classBreakMethodElement = d(), this.nullElement = d(), this.breaksCountElement = d(), this.colorSchemeElement = d(), this.onHeatChartDataPopoverChange = async (e) => {
      try {
        if (e.detail?.value !== void 0) {
          const { contentKind: t } = e.detail, a = e.detail.value;
          switch (t) {
            case l.aggregation:
              this.model.aggregationType = a, a === u.Count || a === u.Sum ? this.model.nullPolicy = g.Zero : this.model.nullPolicy = g.Null;
              break;
            case l.xAxisField:
              this.model.xAxisField = a, this.setDefaultPropertiesForCalendarHeatChart();
              break;
            case l.numericFields:
              this.model.numericFields = [a.trim() || ""], (this.model.numericFields ?? []).length > 0 && this.model.aggregationType === u.Count && this.model.numericFields[0] !== W(this.model.layer).idField && (this.model.aggregationType = u.Sum);
              break;
            case l.calendarType: {
              switch (a) {
                case v.YearByMonthAndDayOfMonth: {
                  const s = {
                    type: h.CalendarDateParts,
                    unit: y.DayOfMonth
                  }, o = {
                    type: h.CalendarDateParts,
                    unit: y.MonthOfYear
                  };
                  this.model.xTemporalBinning = s, this.model.setAxisValueFormat(0, {
                    type: h.DateAxisFormat,
                    intlOptions: { day: "2-digit" }
                  }), this.model.yTemporalBinning = o, this.model.setAxisValueFormat(1, {
                    type: h.DateAxisFormat,
                    intlOptions: { month: "short" }
                  });
                  break;
                }
                case v.WeekByDayOfWeekAndHourOfDay: {
                  const s = {
                    type: h.CalendarDateParts,
                    unit: y.HourOfDay
                  }, o = {
                    type: h.CalendarDateParts,
                    unit: y.DayOfWeek
                  }, { lang: i } = I(this.el ?? document.documentElement), m = w(i), C = U.local().setLocale(i).startOf("week", { useLocaleWeeks: m !== _ }).weekday;
                  this.model.firstDayOfWeek = C, this.model.xTemporalBinning = s, this.model.setAxisValueFormat(0, {
                    type: h.DateAxisFormat,
                    intlOptions: { hour: "numeric", hour12: !1 }
                  }), this.model.yTemporalBinning = o, this.model.setAxisValueFormat(1, {
                    type: h.DateAxisFormat,
                    intlOptions: { weekday: "short" }
                  });
                  break;
                }
                default:
                  break;
              }
              break;
            }
            case l.calendarViewType: {
              this.model.viewType = a;
              break;
            }
            case l.classBreakMethod: {
              this.model.classificationMethod = a, this.updateChartRenderer = !0;
              break;
            }
            default:
              break;
          }
        }
      } catch (t) {
        throw this.arcgisChartsConfigDataChangeError.emit({ error: t, model: this.model }), t;
      }
      this.removeHeatChartDataPopover(), this.requestUpdate();
    }, this.popoverClose = (e) => {
      this.heatChartPopover === e?.target && this.removeHeatChartDataPopover();
    }, this.onModelConfigChange = () => {
      V(this.model?.config) && (this.selectedColorRamp = A.defaultColorRampForCharts), this.requestUpdate();
    }, this.allColorRamps = [], this.onColorRampSelection = (e) => {
      const { ramp: t, isFlipped: a } = e.detail;
      this.isFlipped = a, B(this.selectedColorRamp, t) || (this.selectedColorRamp = t, this.updateChartRenderer = !0, this.updateClassBreaksColor = !0, this.generateAndUpdateClassBreaks());
    }, this.updateClassBreaksColor = !1, this.onEmptyCellNameChange = (e) => {
      const { name: t } = e.detail;
      if (t !== void 0) {
        const s = {
          ...this.model.emptyCell,
          name: t
        };
        this.model.emptyCell = s;
      }
    }, this.onEmptyCellColorChange = (e) => {
      const { color: t } = e.detail;
      if (t !== void 0) {
        const a = this.model.emptyCell, s = {
          ...a,
          symbol: {
            ...a?.symbol,
            type: Z.SFS,
            color: t,
            outline: a?.symbol?.outline && { ...a.symbol.outline, color: t }
          }
        };
        this.model.emptyCell = s;
      }
    }, this.isFlipped = !1, this.availableColorRamps = [], this.updateChartRenderer = !1, this.layerFieldsInfo = [], this.arcgisChartsConfigDataChangeError = M();
  }
  static {
    this.properties = { availableColorRamps: 16, aggregationLabel: 16, selectedColorRamp: 16, updateChartRenderer: 16, messageOverrides: 0, model: 0, layerFieldsInfo: 0, open: 5 };
  }
  static {
    this.styles = ne;
  }
  connectedCallback() {
    super.connectedCallback(), this.loadColorRampFromArcGIS();
  }
  load() {
    this.modelChange(this.model), this.onModelConfigChange();
  }
  willUpdate(e) {
    e.has("model") && this.modelChange(this.model, e.get("model")), this.aggregationLabel = K(this.model.aggregationType, this.commonStrings);
  }
  updated(e) {
    e.has("updateChartRenderer") && this.updateChartRenderer && this.generateAndUpdateClassBreaks();
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this.model.removeEventListener("arcgisChartsModelConfigChange", this.onModelConfigChange);
  }
  loadColorRampFromArcGIS() {
    const e = A.esriColorRamps;
    this.allColorRamps = e, this.availableColorRamps = this.allColorRamps;
  }
  normalizeClassBreakInfosForCompare(e, t) {
    return (e ?? []).map(({ classMinValue: a, classMaxValue: s, label: o, symbol: i }) => ({
      classMinValue: a,
      classMaxValue: s,
      label: o,
      symbol: t ? void 0 : i
    }));
  }
  async generateAndUpdateClassBreaks() {
    let e = [];
    const t = this.model.chartRenderer?.classBreakInfos, a = this.requestedBreaksCount ?? this.model.breaksCount ?? x.classBreaks.breaksCount;
    if (this.model.classificationMethod === b.manual && t?.length && this.selectedColorRamp) {
      e = H(t) ?? [];
      const i = ee({
        numberOfClassBreaks: a,
        selectedColorRamp: this.selectedColorRamp,
        existingClassBreakInfos: t,
        isFlipped: this.isFlipped
      });
      e = te({
        classBreakInfos: e,
        colors: i
      });
    } else if (this.model.classificationMethod !== b.manual) {
      const i = oe(re);
      i && (e = await ae({
        data: i,
        xAxisField: this.model.xAxisField,
        classificationMethod: this.model.classificationMethod,
        breaksCount: this.model.breaksCount,
        layer: this.model.layer,
        selectedColorRamp: this.selectedColorRamp,
        availableColorRamps: this.availableColorRamps,
        existingClassBreakInfos: t,
        // use the color ramp only if the `selectedColorRamp` was not modified by the color ramp popover
        useExistingColors: !this.updateClassBreaksColor,
        // Note: selectedColorRamp already has flip applied if needed (handled by popover component)
        isFlipped: this.isFlipped
      }));
    }
    const s = !this.updateClassBreaksColor, o = !B(this.normalizeClassBreakInfosForCompare(this.model.chartRenderer?.classBreakInfos, s), this.normalizeClassBreakInfosForCompare(e, s));
    if (this.updateChartRenderer && o && (this.model.chartRenderer = {
      type: "classBreaks",
      // TODO (heat-chart) use the correct type
      field: q.valueField,
      classBreakInfos: e
    }, this.model.heatRulesType !== k.Renderer && (this.model.heatRulesType = k.Renderer), this.model.classificationMethod !== b.manual)) {
      const i = e.length || a;
      this.model.breaksCount !== i && (this.model.breaksCount = i);
    }
    this.updateChartRenderer = !1, this.updateClassBreaksColor = !1;
  }
  modelChange(e, t) {
    t?.removeEventListener("arcgisChartsModelConfigChange", this.onModelConfigChange), e?.addEventListener("arcgisChartsModelConfigChange", this.onModelConfigChange);
  }
  getCorrectedXAxisFieldValue() {
    return Y({
      fieldName: this.model.xAxisField,
      fieldList: this.layerFieldsInfo
    }) ? "" : R(this.layerFieldsInfo, this.model.xAxisField);
  }
  onXAxisFieldSelect(e) {
    this.contentKind = l.xAxisField, this.setupPopover(e);
  }
  onNumericFieldSelect(e) {
    this.contentKind = l.numericFields, this.setupPopover(e);
  }
  onCalendarTypeSelect(e) {
    this.contentKind = l.calendarType, this.setupPopover(e);
  }
  onClassBreakMethodSelect(e) {
    this.contentKind = l.classBreakMethod, this.setupPopover(e);
  }
  onColorSchemeSelect(e) {
    this.contentKind = l.colorScheme, this.setupPopover(e);
  }
  onBreaksCountChange(e) {
    let t = L(e.target.value);
    t < f.min ? t = f.min : t > f.max && (t = f.max), z(t) && (this.breaksCountElement.value && (this.breaksCountElement.value.value = t.toString()), this.requestedBreaksCount = t, this.model.breaksCount = t, this.updateChartRenderer = !0);
  }
  onAggregationSelect(e) {
    this.contentKind = l.aggregation, this.setupPopover(e);
  }
  onNullSelect(e) {
    this.contentKind = l.null, this.setupPopover(e);
  }
  onIncludeLeapDayChange(e) {
    const t = e.target.checked;
    this.model.includeLeapDay = t;
  }
  onNullPolicyChange(e) {
    this.model.nullPolicy = e.target.selectedItem.value;
  }
  setupPopover(e) {
    e.stopImmediatePropagation(), this.removeHeatChartDataPopover();
    let t, a, s, o = this.isFlipped;
    switch (this.contentKind) {
      case l.aggregation:
        t = this.aggregationElement.value, a = this._messages.aggregationHeader, s = this.model.aggregationType;
        break;
      case l.xAxisField:
        t = this.xAxisFieldElement.value, a = this._messages.xAxisField, s = this.model.xAxisField;
        break;
      case l.numericFields:
        t = this.numericFieldsElement.value, a = this._messages.numericField, s = this.model.numericFields?.[0];
        break;
      case l.calendarType:
        t = this.calendarTypeElement.value, a = this._messages.calendarType, s = $(this.model);
        break;
      case l.calendarViewType:
        t = this.calendarViewTypeElement.value, a = this._messages.viewType, s = this.model.viewType;
        break;
      case l.classBreakMethod:
        t = this.classBreakMethodElement.value, a = this._messages.method, s = this.model.classificationMethod;
        break;
      case l.colorScheme:
        t = this.colorSchemeElement.value, a = this._messages.colorScheme;
        const i = se(this.model.chartRenderer?.classBreakInfos, this.availableColorRamps);
        s = this.selectedColorRamp?.name ?? i?.name;
        const m = i ? i.colorsForClassBreaks.find((C) => C.numClasses === this.model.breaksCount)?.colors : void 0;
        o = m ? ie(m, this.model.chartRenderer?.classBreakInfos) : o;
        break;
      case l.null:
        t = e.target, a = this._messages.null;
        break;
    }
    this.heatChartPopover = P(r`<arcgis-charts-config-heat-chart-popover .headingTitle=${a} .referenceElement=${t} open .contentKind=${this.contentKind} .model=${this.model} .layerFieldsInfo=${this.layerFieldsInfo} .selectedContent=${s} @arcgisChartsConfigHeatChartDataPopoverChange=${this.onHeatChartDataPopoverChange} @arcgisChartsConfigPopoverClose=${this.popoverClose} .colorRamps=${this.availableColorRamps} @arcgisChartsConfigHeatChartColorRampChange=${this.onColorRampSelection} @arcgisChartsConfigPopoverEmptyCellColorChange=${this.onEmptyCellColorChange} @arcgisChartsConfigPopoverEmptyCellNameChange=${this.onEmptyCellNameChange} .isFlipped=${o}></arcgis-charts-config-heat-chart-popover>`), !document.body.contains(this.heatChartPopover) && this.heatChartPopover !== null && document.body.appendChild(this.heatChartPopover);
  }
  removeHeatChartDataPopover() {
    this.heatChartPopover !== null && (this.heatChartPopover.open = !1, this.heatChartPopover = J(this.heatChartPopover));
  }
  setDefaultPropertiesForCalendarHeatChart() {
    if (!G(this.model?.config)) {
      if (this.model.xTemporalBinning === void 0) {
        const e = {
          type: h.CalendarDateParts,
          unit: y.DayOfMonth
        };
        this.model.xTemporalBinning = e;
      }
      if (this.model.yAxisField = this.model.xAxisField, this.model.setYAxisSortOrder(j.Desc), this.model.yTemporalBinning === void 0) {
        const e = {
          type: h.CalendarDateParts,
          unit: y.MonthOfYear
        };
        this.model.yTemporalBinning = e, this.model.setAxisValueFormat(1, { type: h.DateAxisFormat, intlOptions: { month: "short" } });
      }
      this.model.classificationMethod === void 0 && (this.model.classificationMethod = b.naturalBreaks), this.model.heatRulesType !== k.Renderer && (this.model.heatRulesType = k.Renderer), this.model.viewType === void 0 && (this.model.viewType = X.singleCalendarView), (this.model.aggregationType === u.Count || this.model.aggregationType === u.Sum) && this.model.nullPolicy !== g.Zero && (this.model.nullPolicy = g.Zero);
    }
  }
  renderXAxisFieldSelect() {
    const e = this.getCorrectedXAxisFieldValue();
    return r`<arcgis-charts-config-field-select .label=${e} @click=${this.onXAxisFieldSelect} ${p(this.xAxisFieldElement)}></arcgis-charts-config-field-select>`;
  }
  renderAggregation() {
    return r`<arcgis-charts-config-field-select .label=${this.model.aggregationType === u.NoAggregation ? this._messages.noAggregation : this.aggregationLabel} @click=${this.onAggregationSelect} ${p(this.aggregationElement)}></arcgis-charts-config-field-select>`;
  }
  renderNumericFieldsSelect() {
    const e = this.model.numericFields?.[0] === this.model.layer?.objectIdField ? "" : R(this.layerFieldsInfo, this.model.numericFields?.[0]);
    return r`<arcgis-charts-config-field-select .label=${e} @click=${this.onNumericFieldSelect} ${p(this.numericFieldsElement)}></arcgis-charts-config-field-select>`;
  }
  renderCalendarTypeSelect() {
    const e = $(this.model) ?? "", t = {
      weekByDayOfWeekAndHourOfDay: this._messages.weekByDayOfWeekAndHourOfDay,
      yearByMonthAndDayOfMonth: this._messages.yearByMonthAndDayOfMonth
    }, a = e ? t[e] ?? "" : "";
    return r`<arcgis-charts-config-field-select .label=${a} @click=${this.onCalendarTypeSelect} ${p(this.calendarTypeElement)}></arcgis-charts-config-field-select>`;
  }
  renderClassBreakMethodSelect() {
    const e = {
      equalInterval: this._messages.classBreaksMethod?.equalInterval,
      manual: this._messages.classBreaksMethod?.manual,
      naturalBreaks: this._messages.classBreaksMethod?.naturalBreaks,
      quantile: this._messages.classBreaksMethod?.quantile
    }, t = this.model.classificationMethod ? e[N(this.model.classificationMethod)] ?? "" : "";
    return r`<arcgis-charts-config-field-select .label=${t} @click=${this.onClassBreakMethodSelect} ${p(this.classBreakMethodElement)}></arcgis-charts-config-field-select>`;
  }
  renderColorRampSelect() {
    const e = this.model.chartRenderer?.classBreakInfos?.map((t) => {
      const a = t !== void 0 ? le(t.symbol.color) : "#FFFFFF";
      return r`<div class=${n(c.colorRampSegment)} style=${F({ backgroundColor: a, width: `${100 / this.model.breaksCount}%` })}></div>`;
    });
    return r`<arcgis-charts-config-field-select label @click=${this.onColorSchemeSelect} ${p(this.colorSchemeElement)}><div slot=fieldSelectSlot class=${n(c.colorRamp)}>${e}</div></arcgis-charts-config-field-select>`;
  }
  renderClassBreaksTable() {
    const e = this.model.chartRenderer?.classBreakInfos ?? [];
    return r`<calcite-table caption="Simple table"><calcite-table-row slot=table-header><calcite-table-header .heading=${this._messages.symbol}></calcite-table-header><calcite-table-header .heading=${this._messages.upperValue}></calcite-table-header></calcite-table-row>${e.map((t) => r`<calcite-table-row><calcite-table-cell><calcite-swatch label scale=m .color=${`rgba(${t.symbol.color?.[0]}, ${t.symbol.color?.[1]}, ${t.symbol.color?.[2]}, ${t.symbol.color?.[3] / 255})`}></calcite-swatch></calcite-table-cell><calcite-table-cell>${t.label}</calcite-table-cell></calcite-table-row>`)}</calcite-table>`;
  }
  renderNullUI() {
    const e = this.model.emptyCell, t = this._messages.null, a = e?.symbol?.color ?? x.grayColor, [s, o, i, m] = [...a], C = `rgba(${s},${o},${i},${m / 255})`;
    return r`<calcite-list label class=${n(c.list)} selection-mode=none ${p(this.nullElement)}><calcite-list-item .label=${t} .value=${t} @calciteListItemSelect=${this.onNullSelect}><calcite-icon icon=square-f style=${F({ color: C })} slot=content-end></calcite-icon></calcite-list-item></calcite-list>`;
  }
  renderEmptyBins() {
    return r`<calcite-radio-button-group name=empty-bins layout=vertical @calciteRadioButtonGroupChange=${this.onNullPolicyChange}><calcite-label layout=inline><calcite-radio-button .value=${g.Zero} .checked=${this.model.nullPolicy === g.Zero}></calcite-radio-button>${this._messages.treatAsZero}</calcite-label><calcite-label layout=inline><calcite-radio-button .value=${g.Null} .checked=${this.model.nullPolicy === g.Null}></calcite-radio-button>${this._messages.treatAsNull}</calcite-label></calcite-radio-button-group>`;
  }
  render() {
    const e = this.renderXAxisFieldSelect(), t = this.renderAggregation(), a = this.renderNumericFieldsSelect(), s = this.renderCalendarTypeSelect(), o = this.renderClassBreakMethodSelect(), i = this.renderColorRampSelect(), m = this.renderClassBreaksTable(), C = this.renderNullUI(), S = this.renderEmptyBins();
    return r`<calcite-label class=${n(c.label)}>${this._messages.dateRequired}${e}</calcite-label><calcite-label class=${n(c.label)}>${this._messages.calendarType}${s}</calcite-label><calcite-label class=${n(c.label)}>${this._messages.aggregation}${t}</calcite-label><calcite-label class=${n(c.label)}>${this._messages.numericField}${a}</calcite-label><calcite-label class=${n(c.label)}>${this._messages.method}${o}</calcite-label><calcite-label class=${n(c.label)}>${this._messages.numberOfClasses}<calcite-input type=number .min=${f.min} .max=${f.max} .disabled=${this.model.classificationMethod === void 0 || this.model.classificationMethod === b.manual} step=1 .value=${Q(this.model.breaksCount, 5)} @calciteInputInput=${this.onBreaksCountChange} ${p(this.breaksCountElement)}></calcite-input></calcite-label><calcite-label class=${n(c.label)}>${this._messages.colorScheme}${i}</calcite-label>${C}<calcite-accordion class=${n(c.accordion)} appearance=transparent selection-mode=single><calcite-accordion-item .heading=${this._messages.classBreaks}>${m}</calcite-accordion-item></calcite-accordion><calcite-label class=${n(c.label)}>${this._messages.emptyBins}${S}</calcite-label>${$(this.model) === v.YearByMonthAndDayOfMonth ? r`<calcite-label class=${n(c.label)} layout=inline-space-between>${this._messages.includeLeapDay}<calcite-switch .checked=${this.model.includeLeapDay} @calciteSwitchChange=${this.onIncludeLeapDayChange}></calcite-switch></calcite-label>` : null}`;
  }
}
D("arcgis-charts-config-heat-chart-data", ce);
export {
  ce as ArcgisChartsConfigHeatChartData
};
