/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
import { c as P } from "../../chunks/runtime.js";
import "@arcgis/toolkit/intl";
import { cloneDeep as T, isEmpty as F, toNumber as $ } from "lodash-es";
import "luxon";
import "d3-array";
import "@arcgis/toolkit/type";
import { W as f } from "../../chunks/series-types.js";
import { f as v } from "../../chunks/rest-js-object-literals.js";
import { bB as L, d3 as b, aK as z, ar as A } 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 C } from "../../chunks/popover-ui-utils.js";
import { S as a, f as d } from "../../chunks/interfaces.js";
import { d as k, s as m } from "../../chunks/store.js";
import { i as S, m as g, k as M, s as y, D as w, U as u } from "../../chunks/chart-ui-utils2.js";
import { u as x } from "../../chunks/useT9n.js";
import { css as V, html as r } from "lit";
import { createRef as h, ref as c } from "lit/directives/ref.js";
import { LitElement as _, createEvent as E, renderElement as D, safeClassMap as i, safeStyleMap as I } from "@arcgis/lumina";
const l = {
  label: "label",
  r2: "r2",
  numberInput: "number-input",
  iconSelect: "icon-select",
  sectionLabel: "section-label",
  switchElement: "switch-element",
  sectionContainer: "section-container",
  multiInputSection: "multi-input-section",
  dimText: "dim-text"
}, N = V`.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)}:host .number-input{margin-bottom:.5rem;display:flex}:host .number-input>div{width:100%}calcite-list-item{margin-left:var(--arcgis-charts-config-margin-minor);margin-right:var(--arcgis-charts-config-margin-minor)}calcite-slider{margin-top:-1.5rem}.r2{margin:var(--arcgis-charts-config-margin-major) var(--arcgis-charts-config-margin-minor)}.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}.section-container{display:flex;flex-direction:column}.icon-select{cursor:pointer}.section-label{display:flex;margin:var(--arcgis-charts-config-margin-major) var(--arcgis-charts-config-margin-minor);justify-content:space-between;align-items:center;font-weight:var(--calcite-font-weight-medium);font-size:var(--calcite-font-size-0)}.switch-element{margin-right:var(--arcgis-charts-config-margin-minor)}.multi-input-section{display:flex;justify-content:space-between;align-items:center}`;
class K extends _ {
  constructor() {
    super(...arguments), this._messages = x(), this.commonStrings = x({ name: "common", blocking: !0 }), this.scatterplotPopover = null, this.selectColorElement = h(), this.selectTrendLineElement = h(), this.xAxisElement = h(), this.yAxisElement = h(), this.tooltipFieldElement = h(), this.sizeVariableElement = h(), this.colorModeElement = h(), this.symbolSizeModeElement = h(), this.minSizeInputElement = h(), this.maxSizeInputElement = h(), this.items = [], this.setTrendLineSymbol = (e) => {
      const t = e.detail;
      this.model.linearTrendSymbol = T(t);
    }, this.setFixedSymbolRGBAColor = (e) => {
      const t = e.detail, [s, o, n] = t, p = A * 255;
      this.model.fixedMarkerSymbol = {
        ...this.model.fixedMarkerSymbol,
        color: [s, o, n, p]
      };
    }, this.setXYField = (e) => {
      try {
        const t = e.detail;
        k(m), this.contentKind === a.xAxisField ? this.model.xAxisField = t : this.model.yAxisField = t, this.removeScatterplotPopover();
      } catch (t) {
        throw t instanceof Error && this.arcgisChartsConfigDataChangeError.emit({ error: t, model: this.model }), t;
      }
    }, this.setAdditionalTooltipField = (e) => {
      const t = e.detail;
      this.model.additionalTooltipField = t, this.removeScatterplotPopover();
    }, this.setSizeVariableField = (e) => {
      try {
        const t = e.detail;
        t ? this.model.sizePolicy = {
          ...this.model.sizePolicy,
          type: f.SizePolicy,
          field: t
        } : this.model.sizePolicy = void 0, m.scatterplotData[m.selectedChartId] = {
          ...m.scatterplotData[m.selectedChartId],
          sizePolicyField: this.model.sizePolicy?.field ?? void 0
        }, this.removeScatterplotPopover();
      } catch (t) {
        throw t instanceof Error && this.arcgisChartsConfigDataChangeError.emit({ error: t, model: this.model }), t;
      }
    }, this.closeScatterplotPopover = (e) => {
      this.scatterplotPopover === e?.target && (this.contentKind = a.none, this.removeScatterplotPopover());
    }, this.onModelConfigChange = () => {
      this.requestUpdate();
      const { minSize: e, maxSize: t } = this.model.sizePolicy ?? {};
      this.minSizeInputElement.value !== void 0 && e !== void 0 && (this.minSizeInputElement.value.value = `${e}`, S(this.minSizeInputElement.value.value, this.minSizeInputElement.value.min, this.minSizeInputElement.value.max) ? g({
        inputElement: this.minSizeInputElement.value,
        status: u.IDLE
      }) : g({
        inputElement: this.minSizeInputElement.value,
        status: u.INVALID
      })), this.maxSizeInputElement.value !== void 0 && t !== void 0 && (this.maxSizeInputElement.value.value = `${t}`, S(this.maxSizeInputElement.value.value, this.maxSizeInputElement.value.min, this.maxSizeInputElement.value.max) ? g({
        inputElement: this.maxSizeInputElement.value,
        status: u.IDLE
      }) : g({
        inputElement: this.maxSizeInputElement.value,
        status: u.INVALID
      }));
    }, this.segmentedControlRef = (e) => {
      e && (e.focus = () => {
      }, this.items.push(e));
    }, this.layerFieldsInfo = [], this.arcgisChartsConfigDataChangeError = E(), this.arcgisChartsConfigScatterplotPopoverChange = E();
  }
  static {
    this.properties = { selectedElement: 16, selectedSizeType: 16, messageOverrides: 0, model: 0, r2: 9, layerFieldsInfo: 0, isTableLayer: 5 };
  }
  static {
    this.styles = N;
  }
  load() {
    this.modelChange(this.model), this.onModelConfigChange(), this.defaultR2Label = L(this.commonStrings);
  }
  willUpdate(e) {
    e.has("model") && (this.updateSymbolSizeInfoInAppState(), this.modelChange(this.model, e.get("model"))), e.has("selectedElement") && this.openPopover();
  }
  loaded() {
    this.loadedAsync();
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this.removeScatterplotPopover(), this.model.removeEventListener("arcgisChartsModelConfigChange", this.onModelConfigChange);
  }
  async loadedAsync() {
    await (async (t) => await new Promise((s) => setTimeout(() => s(), t)))(250), this.items.forEach((t) => {
      delete t.focus;
    });
  }
  updateSymbolSizeInfoInAppState() {
    this.selectedSizeType = this.getCurrentSymbolSizeType(), this.selectedSizeType === d.Proportional && (m.scatterplotData[m.selectedChartId] = {
      ...m.scatterplotData[m.selectedChartId],
      sizePolicyField: this.model.sizePolicy?.field
    });
  }
  openPopover() {
    (typeof this.selectedElement == "string" || !F(this.selectedElement)) && this.setupPopover();
  }
  modelChange(e, t) {
    t?.removeEventListener("arcgisChartsModelConfigChange", this.onModelConfigChange), e?.addEventListener("arcgisChartsModelConfigChange", this.onModelConfigChange);
  }
  setShowTrendLine(e) {
    const t = e.target.checked;
    this.model.showLinearTrend = t, !t && this.contentKind === a.trendLine && this.closeScatterplotPopover(e);
  }
  symbolSizeChange(e) {
    const t = e.target, { value: s } = t;
    if (s !== void 0 && S(s, t.min, t.max)) {
      const o = Number.parseInt(s), n = this.model.sizePolicy, p = this.model.fixedMarkerSymbol;
      switch (t.name) {
        case "fixed-symbol-size":
          p !== void 0 && (this.model.fixedMarkerSymbol = {
            ...p,
            size: o
          });
          break;
        case "proportional-symbol-min-size":
          n !== void 0 && (this.model.sizePolicy = {
            ...n,
            minSize: o
          });
          break;
        case "proportional-symbol-max-size":
          n !== void 0 && (this.model.sizePolicy = {
            ...n,
            maxSize: o
          });
          break;
      }
      g({
        inputElement: t,
        status: u.IDLE
      });
    } else
      g({
        inputElement: t,
        status: u.INVALID
      });
  }
  symbolSizeRangeSliderInput(e) {
    const t = e.target, { minValue: s, maxValue: o } = t, n = this.model.sizePolicy;
    n !== void 0 && (this.model.sizePolicy = {
      ...n,
      minSize: s,
      maxSize: o
    }, this.minSizeInputElement.value !== void 0 && (this.minSizeInputElement.value.value = `${s}`), this.maxSizeInputElement.value !== void 0 && (this.maxSizeInputElement.value.value = `${o}`));
  }
  changeColorTypeToggle() {
    const e = this.colorModeElement.value?.selectedItem?.value;
    this.model.colorMatch = e === this._messages.useLayerColors;
  }
  changeSymbolSizeTypeToggle() {
    const e = this.symbolSizeModeElement.value?.value;
    this.selectedSizeType = e;
    const t = m.scatterplotData[m.selectedChartId]?.sizePolicyField;
    e === d.Proportional && t !== void 0 ? this.model.sizePolicy = {
      ...this.model.sizePolicy,
      type: f.SizePolicy,
      field: t
    } : e === d.Fixed && (this.model.sizePolicy = {
      ...this.model.sizePolicy,
      type: f.SizePolicy,
      field: ""
    });
  }
  changeElementStyle(e) {
    e.stopImmediatePropagation();
    let t = e.target;
    t.localName === "calcite-icon" && (t = t.parentElement), t.value === "selectColor" ? (this.contentKind = a.symbol, this.selectedElement = this.model.fixedMarkerSymbol?.color) : t.value === "selectTrendLine" && (this.contentKind = a.trendLine, this.selectedElement = this.model.linearTrendSymbol);
  }
  onXVariableSelectChange(e) {
    e.stopImmediatePropagation(), this.contentKind = a.xAxisField, this.selectedElement = this.model.xAxisField;
  }
  onYVariableSelectChange(e) {
    e.stopImmediatePropagation(), this.contentKind = a.yAxisField, this.selectedElement = this.model.yAxisField;
  }
  onAdditionalTooltipFieldSelectChange(e) {
    e.stopImmediatePropagation(), this.contentKind = a.additionalTooltipFields, this.selectedElement = this.model.additionalTooltipField?.[0] ?? "";
  }
  onSizeVariableSelectChange(e) {
    e.stopImmediatePropagation(), this.contentKind = a.sizeVariable, this.selectedElement = this.model.sizePolicy?.field ?? "";
  }
  setupPopover() {
    this.scatterplotPopover = C(this.scatterplotPopover);
    const e = [...this.layerFieldsInfo];
    let t, s, o, n = "trailing";
    switch (this.contentKind) {
      case a.xAxisField:
        t = this.xAxisElement.value, o = this.model.xAxisField, s = this._messages.selectAField;
        break;
      case a.yAxisField:
        t = this.yAxisElement.value, o = this.model.yAxisField, s = this._messages.selectAField;
        break;
      case a.sizeVariable:
        t = this.sizeVariableElement.value, o = this.model.sizePolicy?.field ?? "", s = this._messages.selectAField;
        break;
      case a.additionalTooltipFields:
        t = this.tooltipFieldElement.value, o = this.model.additionalTooltipField?.[0] ?? "", s = this._messages.selectAField;
        break;
      case a.symbol:
      case a.trendLine: {
        const p = this.selectedElement;
        o = this.selectedElement, n = "leading", Array.isArray(this.selectedElement) ? t = this.selectColorElement.value : p?.type === v.SLS && (t = this.selectTrendLineElement.value);
        break;
      }
      default:
        this.contentKind = a.none, this.removeScatterplotPopover();
        break;
    }
    this.scatterplotPopover = D(r`<arcgis-charts-config-scatter-plot-popover .headingTitle=${s} .referenceElement=${t} open .contentKind=${this.contentKind} .layerFieldsInfo=${e} .selectedContent=${o} .placement=${n} @arcgisChartsConfigPopoverClose=${this.closeScatterplotPopover} @arcgisChartsConfigScatterplotFillColorChange=${this.setFixedSymbolRGBAColor} @arcgisChartsConfigScatterplotLineStyleChange=${this.setTrendLineSymbol} @arcgisChartsConfigScatterplotXYFieldChange=${this.setXYField} @arcgisChartsConfigScatterplotSizeVariableFieldChange=${this.setSizeVariableField} @arcgisChartsConfigScatterplotAdditionalTooltipFieldChange=${this.setAdditionalTooltipField}></arcgis-charts-config-scatter-plot-popover>`), !document.body.contains(this.scatterplotPopover) && this.scatterplotPopover !== null && document.body.appendChild(this.scatterplotPopover);
  }
  removeScatterplotPopover() {
    this.scatterplotPopover !== null && (this.scatterplotPopover = C(this.scatterplotPopover)), this.selectedElement = void 0;
  }
  getCurrentSymbolSizeType() {
    const e = this.model.sizePolicy;
    return e === void 0 || e.field === "" ? d.Fixed : d.Proportional;
  }
  renderXVariable() {
    return r`<arcgis-charts-config-field-select .label=${b(this.layerFieldsInfo, this.model.xAxisField ?? "")} @click=${this.onXVariableSelectChange} ${c(this.xAxisElement)}></arcgis-charts-config-field-select>`;
  }
  renderYVariable() {
    return r`<arcgis-charts-config-field-select .label=${b(this.layerFieldsInfo, this.model.yAxisField ?? "")} @click=${this.onYVariableSelectChange} ${c(this.yAxisElement)}></arcgis-charts-config-field-select>`;
  }
  renderTooltipField() {
    return r`<arcgis-charts-config-field-select .disabled=${this.model.dataStore.aggregated} .label=${b(this.layerFieldsInfo, this.model.additionalTooltipField?.[0] ?? "")} @click=${this.onAdditionalTooltipFieldSelectChange} ${c(this.tooltipFieldElement)}></arcgis-charts-config-field-select>`;
  }
  renderStatistics() {
    const [e, t, s, o] = [...this.model.linearTrendSymbol?.color ?? z(0)];
    return r`<div class=${i(l.sectionContainer)}><calcite-label class=${i(l.label)} layout=inline-space-between>${this._messages.showLinearTrend}<calcite-switch class=${i(l.switchElement)} .checked=${this.model.showLinearTrend} @calciteSwitchChange=${this.setShowTrendLine}></calcite-switch></calcite-label><calcite-list label selection-mode=single selection-appearance=border><calcite-list-item .label=${this._messages.trendLineStyle} value=selectTrendLine .hidden=${!this.model.showLinearTrend} .selected=${this.selectedElement?.type === v.SLS} @click=${this.changeElementStyle} ${c(this.selectTrendLineElement)}><calcite-icon slot=content-end icon=line-solid style=${I({ color: `rgba(${e},${t},${s},${o / 255})` })} class=${i(l.iconSelect)} @click=${this.changeElementStyle}></calcite-icon></calcite-list-item></calcite-list><div class=${i(l.r2)} .hidden=${!this.model.showLinearTrend}>${`${this._messages.r2}: ${Number.isNaN(this.r2) ? this.defaultR2Label : M(this.r2, w)}`}</div></div>`;
  }
  renderFixedSymbol() {
    return r`<calcite-label class=${i(l.label)}>${this._messages.size}<calcite-input type=number name=fixed-symbol-size class=${i(l.numberInput)} min=1 max=100 step=1 .value=${y(this.model.fixedMarkerSymbol?.size)} @calciteInputInput=${this.symbolSizeChange}></calcite-input></calcite-label>`;
  }
  renderSizeVariable() {
    return r`<arcgis-charts-config-field-select .label=${b(this.layerFieldsInfo, this.model.sizePolicy?.field ?? "")} .invalid=${this.layerFieldsInfo.find((e) => e.name === this.model.sizePolicy?.field) === void 0} @click=${this.onSizeVariableSelectChange} ${c(this.sizeVariableElement)}></arcgis-charts-config-field-select>`;
  }
  renderMinSizeInput() {
    return r`<calcite-input type=number name=proportional-symbol-min-size class=${i(l.numberInput)} min=1 .max=${this.model.sizePolicy?.maxSize ?? 100} step=1 .value=${y(this.model.sizePolicy?.minSize)} @calciteInputInput=${this.symbolSizeChange} ${c(this.minSizeInputElement)}></calcite-input>`;
  }
  renderMaxSizeInput() {
    return r`<calcite-input type=number name=proportional-symbol-max-size class=${i(l.numberInput)} .min=${this.model.sizePolicy?.minSize ?? 1} max=100 step=1 .value=${y(this.model.sizePolicy?.maxSize)} @calciteInputInput=${this.symbolSizeChange} ${c(this.maxSizeInputElement)}></calcite-input>`;
  }
  renderProportionalSymbol() {
    return r`<div class=${i(l.sectionContainer)}><calcite-label class=${i(l.label)}>${this._messages.numberRequired}${this.renderSizeVariable()}</calcite-label><div class=${i(l.multiInputSection)}><calcite-label class=${i(l.label)}>${this._messages.minSize}${this.renderMinSizeInput()}</calcite-label><calcite-label class=${i(l.label)}>${this._messages.maxSize}${this.renderMaxSizeInput()}</calcite-label></div><calcite-label><calcite-slider min=1 max=100 .minValue=${$(y(this.model.sizePolicy?.minSize))} .maxValue=${$(y(this.model.sizePolicy?.maxSize))} step=1 @calciteSliderInput=${this.symbolSizeRangeSliderInput}></calcite-slider></calcite-label></div>`;
  }
  renderSymbolSizeType() {
    return r`<calcite-label class=${i(l.label)}>${this._messages.size}<calcite-segmented-control name=symbolSizeType layout=horizontal scale=s @calciteSegmentedControlChange=${this.changeSymbolSizeTypeToggle} ${c(this.symbolSizeModeElement)}><calcite-segmented-control-item .value=${d.Fixed} .checked=${d.Fixed === this.selectedSizeType} ${c(this.segmentedControlRef)}>${this._messages.fixed}</calcite-segmented-control-item><calcite-segmented-control-item .value=${d.Proportional} .checked=${d.Proportional === this.selectedSizeType} ${c(this.segmentedControlRef)}>${this._messages.proportional}</calcite-segmented-control-item></calcite-segmented-control></calcite-label>`;
  }
  renderSymbol() {
    const [e, t, s, o] = [...this.model.fixedMarkerSymbol?.color ?? z(0)];
    return r`<div class=${i(l.sectionContainer)}>${this.renderSymbolSizeType()}${this.selectedSizeType === d.Proportional ? this.renderProportionalSymbol() : this.renderFixedSymbol()}<calcite-label class=${i(l.label)}>${this._messages.color}${this.isTableLayer !== !0 ? r`<calcite-segmented-control name=layerColor layout=horizontal scale=s @calciteSegmentedControlChange=${this.changeColorTypeToggle} ${c(this.colorModeElement)}><calcite-segmented-control-item .value=${this._messages.useLayerColors} .checked=${this.model.colorMatch} ${c(this.segmentedControlRef)}>${this._messages.useLayerColors}</calcite-segmented-control-item><calcite-segmented-control-item .value=${this._messages.singleColor} .checked=${!this.model.colorMatch} ${c(this.segmentedControlRef)}>${this._messages.singleColor}</calcite-segmented-control-item></calcite-segmented-control>` : null}</calcite-label><calcite-list label selection-mode=single selection-appearance=border><calcite-list-item .label=${this._messages.color} value=selectColor .hidden=${this.model.colorMatch && this.isTableLayer !== !0} .selected=${Array.isArray(this.selectedElement)} @click=${this.changeElementStyle} ${c(this.selectColorElement)}><calcite-icon slot=content-end icon=circle-f style=${I({ color: `rgba(${e},${t},${s},${o / 255})` })} class=${i(l.iconSelect)} @click=${this.changeElementStyle}></calcite-icon></calcite-list-item></calcite-list></div>`;
  }
  render() {
    return r`<h3 class=${i(l.sectionLabel)}>${this._messages.variables}</h3><calcite-label class=${i(l.label)}>${this._messages.xAxisNumber}${this.renderXVariable()}</calcite-label><calcite-label class=${i(l.label)}>${this._messages.yAxisNumber}${this.renderYVariable()}</calcite-label><calcite-label class=${i(l.label)}><span class=${i(this.model.dataStore.aggregated ? l.dimText : "")}>${this._messages.additionalTooltipFields}</span>${this.renderTooltipField()}</calcite-label><h3 class=${i(l.sectionLabel)}>${this._messages.statistics}</h3>${this.renderStatistics()}<h3 class=${i(l.sectionLabel)}>${this._messages.symbol}</h3>${this.renderSymbol()}`;
  }
}
P("arcgis-charts-config-scatter-plot-data", K);
export {
  K as ArcgisChartsConfigScatterplotData
};
