import { jsx as p, jsxs as ue } from "react/jsx-runtime";
import { useState as V, useRef as Qa, useEffect as me } from "react";
import { Container as pe } from "semantic-ui-react";
import Za from "../data/DataProvider.js";
import Oa from "../data/DataConsumer.js";
import ja from "../../utils/deviceType.js";
import er from "./Pie.js";
import "immutable";
import tr from "./Radar.js";
import ar from "./Bar.js";
import rr from "./Line.js";
import { PostContent as or } from "@devgateway/wp-react-lib";
import Z from "./data/index.js";
import nr from "./CSVDataFrame.js";
import sr from "./colors/ColorProvider.js";
import st from "./Messages.js";
import { connect as ir } from "react-redux";
import { injectIntl as lr } from "react-intl";
const dr = (v) => {
  console.log("manual colors...", v["data-manual-colors"]);
  let {
    parent: he,
    editing: i = !1,
    unique: O,
    childContent: L,
    categories: G,
    injectedMeasures: l,
    "data-app": o = "csv",
    "data-dvz-proxy-dataset-id": ge,
    "data-group": fe = "default",
    "data-height": X = 500,
    "data-type": B = "bar",
    //'data-source': source = 'gender/smoke',f
    "data-dimension1": P,
    "data-dimension2": be,
    "data-dimension3": mr,
    "data-color-by": E = "index",
    "data-scheme": j = "system",
    "data-group-mode": it = "grouped",
    "data-left-legend": lt = "Left Legend",
    "data-legend-label": dt = "",
    "data-bottom-legend": ct = "Bottom Legend",
    "data-dualmode": ut,
    "data-legend-position": we = "right",
    "data-show-legends": xe = "true",
    "data-data-source-label": pr = "Source",
    "data-chart-data-source": hr = "Data Source",
    "data-toggle-info-label": gr = "Info Graphic",
    "data-toggle-chart-label": fr = "Chart",
    //'data-number-format': format = '{"style":"percent", "minimumFractionDigits": 1, "maximumFractionDigits": 1}',
    "data-tick-rotation": u = 0,
    "data-tick-color": mt = "rgb(92,93,99)",
    "data-measures": pt = "{}",
    "data-format": br = "{}",
    "data-csv": ht = "",
    "data-margin-left": gt = 50,
    "data-margin-top": ft = 25,
    "data-margin-right": bt = 25,
    "data-margin-bottom": wt = 25,
    "data-start-angle": xt = 0,
    "data-end-angle": vt = 360,
    "data-view-mode": ve = "info",
    "data-filters": Lt = "[]",
    //filters
    "data-tooltip-html": yt = "",
    "data-layout": ee = "vertical",
    "data-reverse": Le = "false",
    "data-offset-y": Tt = "-40",
    "data-line-layer-enabled": ye = "false",
    //"data-csv-line-layer-data": csvLineLayerData = "",
    //"data-csv-line-color": lineColor = "#000000",
    //"data-csv-line-tooltip": lineTooltip = "",
    //"data-csv-line-title": lineTitle = "",
    "data-overlays": kt = "[]",
    "data-max-value": Ct = "auto",
    "data-value-scale": Mt = "linear",
    "data-swap": U = "false",
    "data-no-data-message": It = "No data matches your selection",
    "data-bar-color": Dt = "rgb(0,0,0)",
    "data-override-tick-color": Te = "false",
    "data-fixed-min-value": At = 0,
    "data-fixed-max-value": Rt = 0,
    "data-bar-padding": Ft = 0.15,
    "data-bar-label-position": Bt = "middle",
    "data-line-label-position": Pt = "none",
    "data-show-grid": ke = "true",
    "data-include-overall": Ce = "false",
    "data-bar-inner-padding": Et = 0.7,
    "data-x-label-color": Nt = "#000",
    "data-bar-label-color": zt = "#000",
    "data-legend-label-color": Vt = "#000",
    "data-tooltip-enabled": Me = "true",
    "data-use-check-box-background": Ie = "false",
    "data-use-label-background": De = "true",
    "data-highlight-xaxis-line": Ae = "false",
    "data-show-tick-line": Re = "true",
    "data-show-right-axis": Fe = "true",
    "data-manual-colors": Gt = "{}",
    "data-right-legend": Xt = "",
    "data-offset-right": Ut = "40",
    "data-offset-bottom": $t = "40",
    "data-hidden-bars": St = [],
    "data-confidence-intervals": Ht = "[]",
    "data-enable-area": Be = "false",
    "data-area-shading-criteria": Wt = "DEFAULT",
    "data-area-lower-bound": Yt = "",
    "data-area-upper-bound": qt = "",
    "data-show-points": Pe = "true",
    "data-center-label": Jt = "",
    "data-show-arc-labels": Ee = "true",
    "data-show-arc-link-labels": Ne = "true",
    "data-slice-padding": _t = 1,
    "data-center-label-font-weight": Kt = "normal",
    "data-center-label-font-size": Qt = "12",
    "data-center-label-xoffset": Zt = 0,
    "data-center-label-yoffset": Ot = 0,
    "data-group-total-measure": jt = "",
    "data-show-group-total": ze = "true",
    "data-group-total-label": ea = "",
    "data-group-total-format": ta = "{}",
    "data-group-total-label-offset": aa,
    "data-group-total-fixed-position": Ve = "false",
    "data-tooltip-enable-markdown": $ = "false",
    "data-y-axis-tick-values": Ge = "10",
    "data-x-axis-tick-values": Xe = "10",
    "data-enable-grid-y": y = "true",
    "data-enable-grid-x": T = "false",
    "data-offset-text": ra = 0,
    "data-overall-label": te = "Overall",
    "data-min-max-clamp": oa = "false",
    "data-reverse-legend": Ue = "false",
    "data-sort": $e = "default",
    "data-sort-reverse": S = "false",
    "data-sort-second-dimension": Se = "default",
    "data-sort-reverse-second-dimension": H = "false",
    "data-radar-curve": na = "linearClosed",
    "data-radar-fill-opacity": sa = 0.25,
    "data-radar-border-width": ia = 2,
    "data-radar-grid-levels": la = 3,
    "data-radar-grid-shape": da = "circular",
    "data-radar-grid-label-offset": ca = 36,
    "data-radar-enable-dots": He = "true",
    "data-radar-dot-size": ua = 8,
    "data-radar-enable-dot-label": We = "true",
    "data-radar-dot-label-offset": ma = -12,
    "data-mobile-customization": Ye = "{}",
    "data-show-percentage": qe = "false",
    "data-preview-mode": h = "Desktop",
    "data-wait-for-filters": pa = "false",
    "data-line-curve": ha = "linear",
    "data-show-legends-in-columns": Je = "false",
    "data-number-of-legend-columns": ga = 4,
    pageModuleProps: g
  } = v;
  const fa = i, t = JSON.parse(
    decodeURIComponent(Ye)
  ), [ae, ba] = V(
    window.innerWidth <= 1250
  ), b = ae && ((t == null ? void 0 : t.showCustomization) ?? !1);
  g != null && g.previewMode && (g != null && g.editing) && (h = g.previewMode, i = g.editing);
  const wa = ["Tablet"].includes(h) && i, xa = ["Mobile"].includes(h) && i, va = ["Desktop"].includes(h) && i, d = b && h !== "Desktop", c = b && !i, re = () => {
    const e = window.matchMedia(
      "(min-width: 768px) and (max-width: 1250px)"
    ).matches, r = window.matchMedia("(max-width: 767px)").matches;
    switch (!0) {
      case va:
        return u;
      case wa:
        return b ? (t == null ? void 0 : t.tabletXAxisTextRotation) ?? u : u;
      case xa:
        return b ? (t == null ? void 0 : t.mobileXAxisTextRotation) ?? u : u;
      case e:
        return b ? (t == null ? void 0 : t.tabletXAxisTextRotation) ?? u : u;
      case r:
        return b ? (t == null ? void 0 : t.mobileXAxisTextRotation) ?? u : u;
      default:
        return u;
    }
  }, La = re(), [ya, _e] = V(La), Ke = v.intl.locale, W = Qa(null), Qe = (e) => {
    try {
      return fa ? e : decodeURIComponent(e);
    } catch {
      return console.error(`error decoding value:${e}`), e;
    }
  }, k = (e) => {
    try {
      return JSON.parse(Qe(e));
    } catch {
      console.error(`error parsing value:${e}`);
    }
    return null;
  }, Ta = () => {
    const e = k(Gt);
    if (!e) return null;
    const r = e[o];
    if (o === "csv" && r && j === "manual") {
      if (r[E] !== void 0)
        return r;
      if (typeof r == "object" && r !== null && !Array.isArray(r) && Object.values(r).some(
        (m) => typeof m == "string" && (m.startsWith("#") || m.startsWith("rgb"))
      ))
        return { [E]: r };
    }
    return r;
  }, ka = () => k(pt), Ze = () => {
    var e;
    if (a != null && a[o]) {
      let r = (e = a == null ? void 0 : a[o]) == null ? void 0 : e.format;
      if (!r) {
        const n = Object.keys(a == null ? void 0 : a[o]);
        for (let m = 0; m < n.length; m++)
          if (a != null && a[o][n[m]].selected && (a != null && a[o][n[m]].format)) {
            r = a == null ? void 0 : a[o][n[m]].format;
            break;
          }
      }
      return r;
    }
    return a != null && a.csv ? a.csv.format : null;
  }, Ca = () => {
    let e = null;
    return a != null && a[o] ? a[o].useCustomAxisFormat && a[o].customFormat && (e = a[o].customFormat) : a != null && a.csv && a.csv.useCustomAxisFormat && a.csv.customFormat && (e = a.csv.customFormat), e;
  }, Ma = () => a != null && a[o] ? Object.keys(a[o]).map((e) => ({ value: e, ...a[o][e] })).filter((e) => e.selected).map((e) => e.value) : [], Oe = () => {
    const e = {};
    return a != null && a[o] && Object.keys(a[o]).map((n) => ({ value: n, ...a[o][n] })).filter((n) => n.selected && n.hasCustomLabel).forEach((n) => {
      e[n.value] = n.customLabel;
    }), e;
  }, Ia = () => a != null && a[o] ? Object.keys(a[o]).filter(
    (e) => a[o][e].allowSelection
  ) : [];
  let a = ka(), w = Ma(), f = Ze();
  const Da = Ia();
  let oe = lt, ne = Xt, se = Qe(yt);
  if (l != null && l[o]) {
    const e = Object.keys(l[o].measures).map((r) => ({ value: r, ...l[o].measures[r] })).filter((r) => r.selected).map((r) => r.value);
    a = l, w = e, f = Ze(), oe = l.leftTitle, ne = l.rightTitle, l.customTooltip && (se = l.customTooltip);
  }
  const Aa = f ? {
    style: f.style === "compacted" ? "decimal" : f.style,
    notation: f.style === "compacted" ? "compact" : "standard",
    currency: f.currency,
    minimumFractionDigits: parseInt(f.minimumFractionDigits),
    maximumFractionDigits: parseInt(f.maximumFractionDigits)
  } : {
    notation: "standard",
    currency: "USD",
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }, Ra = Ca(), s = k(ta), Fa = {
    style: (s == null ? void 0 : s.style) === "compacted" ? "decimal" : s == null ? void 0 : s.style,
    notation: (s == null ? void 0 : s.style) === "compacted" ? "compact" : "standard",
    currency: s == null ? void 0 : s.currency,
    minimumFractionDigits: parseInt(
      s == null ? void 0 : s.minimumFractionDigits
    ),
    maximumFractionDigits: parseInt(
      s == null ? void 0 : s.maximumFractionDigits
    )
  }, [Ba, wr] = V(ve), Pa = i ? ve : Ba, Ea = {
    scheme: j,
    colorBy: E
  }, Y = i ? X - 80 : X, Na = () => (d || c) && !(t != null && t.showXAxisTitle) ? "" : ct, za = () => d || c ? t != null && t.showYAxisTitle ? oe : "" : oe, Va = () => d || c ? t != null && t.showRightAxisTitle ? ne : "" : ne, Ga = {
    left: za(),
    bottom: Na(),
    right: Va()
  }, q = (e) => {
    if (e === "true" || e === !0)
      return !0;
    if (e === "false" || e === !1)
      return !1;
  }, je = () => {
    q(T) && !q(y) ? (T = !1, y = !0) : !q(T) && q(y) && (T = !0, y = !1);
  }, Xa = () => ee === "horizontal" ? (je(), "vertical") : (je(), "horizontal"), Ua = () => t != null && t.chartLayoutOverride ? Xa() : ee, J = (e, r, n) => e ? Number.parseInt(r) ?? n : n, et = (e, r, n) => e ? r ?? n : n;
  me(() => {
    const e = () => {
      ba(window.innerWidth <= 1250);
      const r = re();
      _e(r);
    };
    return window.addEventListener("resize", e), _e(re()), () => {
      window.removeEventListener("resize", e);
    };
  }, [
    i,
    h,
    b,
    u,
    t == null ? void 0 : t.tabletXAxisTextRotation,
    t == null ? void 0 : t.mobileXAxisTextRotation
  ]);
  const $a = () => {
    const e = ["tablet", "mobile", "midTablet"].includes(
      ja()
    );
    return i && h === "Desktop" ? we : e ? "bottom" : we;
  }, tt = {
    app: o,
    editing: i,
    tickColor: decodeURIComponent(mt),
    tickRotation: ya,
    layout: d || c ? Ua() : ee,
    reverse: Le == !0 || Le == "true",
    showLegends: xe == !0 || xe == "true",
    legendLabel: dt,
    swap: U == !0 || U == "true",
    showGrid: ke == !0 || ke == "true",
    showPercentage: qe == !0 || qe == "true",
    marginLeft: J(
      d || c,
      Number.parseInt(t == null ? void 0 : t.marginLeft),
      parseInt(gt)
    ),
    marginTop: J(
      d || c,
      Number.parseInt(t == null ? void 0 : t.marginTop),
      parseInt(ft)
    ),
    marginRight: J(
      d || c,
      Number.parseInt(t == null ? void 0 : t.marginRight),
      Number.parseInt(bt)
    ),
    marginBottom: J(
      d || c,
      Number.parseInt(t == null ? void 0 : t.marginBottom),
      Number.parseInt(wt)
    ),
    height: `${Y}px`,
    legendPosition: $a(),
    legends: Ga,
    tooltip: $ == !0 || $ == "true" ? se : se.replace(/\r\n/g, "<hr/>").replace(/[\r\n]/g, "<hr/>"),
    colors: Ea,
    groupMode: it,
    format: Aa,
    startAngle: xt,
    endAngle: vt,
    offsetY: Tt,
    // csvLineLayerData,
    // lineColor: decodeURIComponent(lineColor),
    // lineTooltip,
    // lineTitle,
    maxValue: Ct,
    valueScale: Mt,
    categories: G,
    lineLayerEnabled: ye == !0 || ye == "true",
    overlays: k(kt) || [],
    barColor: decodeURIComponent(Dt),
    overrideTickColor: Te == !0 || Te == "true",
    fixedMinValue: At,
    fixedMaxValue: Rt,
    barPadding: et(
      d || c,
      t == null ? void 0 : t.barPadding,
      Ft
    ),
    barLabelPosition: Bt,
    lineLabelPosition: Pt,
    barInnerPadding: et(
      d || c,
      t == null ? void 0 : t.barInnerPadding,
      Et
    ),
    xLabelColor: decodeURIComponent(Nt),
    barLabelColor: decodeURIComponent(zt),
    legendLabelColor: decodeURIComponent(Vt),
    tooltipEnabled: Me == !0 || Me == "true",
    legendLabelBack: De == !0 || De == "true",
    legendCheckBack: Ie == !0 || Ie == "true",
    highlightXAxisLine: Ae == !0 || Ae == "true",
    showTickLine: Re == !0 || Re == "true",
    showRightAxis: Fe == !0 || Fe == "true",
    offsetRight: Ut,
    offsetBottom: $t,
    confidenceIntervals: k(Ht) || [],
    showPoints: Pe == !0 || Pe == "true",
    enableArea: Be == !0 || Be == "true",
    areaShadingCriteria: Wt,
    areaLowerBound: Yt,
    areaUpperBound: qt,
    showGroupTotal: ze == !0 || ze == "true",
    groupTotalMeasure: jt,
    groupTotalLabel: ea,
    groupTotalFormat: Fa,
    groupTotalOffset: aa,
    groupTotalFixedPosition: Ve == !0 || Ve == "true",
    centerLabel: Jt,
    showArcLabels: Ee == !0 || Ee == "true",
    showArcLinkLabels: Ne == !0 || Ne == "true",
    slicePadding: _t,
    centerLabelFontWeight: Kt,
    centerLabelFontSize: Qt,
    centerLabelXOffset: Zt,
    centerLabelYOffset: Ot,
    userMeasures: Da,
    tooltipEnableMarkdown: $ == !0 || $ == "true",
    yAxisTickValues: d || c ? t.yAxisTickValues ?? Ge : Ge,
    xAxisTickValues: d || c ? t.xAxisTickValues ?? Xe : Xe,
    enableGridY: y == !0 || y == "true",
    enableGridX: T == !0 || T == "true",
    offsetText: ra,
    selectedMeasures: w,
    overallLabel: te,
    minMaxClamp: oa,
    reverseLegend: Ue == !0 || Ue == "true",
    customAxisFormat: Ra,
    sort: $e,
    sortReverse: S == !0 || S == "true",
    sortReverseSecondDimension: H == !0 || H == "true",
    radarCurve: na,
    radarFillOpacity: sa,
    radarBorderWidth: ia,
    radarGridLevels: la,
    radarGridShape: da,
    radarGridLabelOffset: ca,
    radarEnableDots: He == !0 || He == "true",
    radarDotSize: ua,
    radarEnableDotLabel: We == !0 || We == "true",
    radarDotLabelOffset: ma,
    sortSecondDimension: Se,
    mobileCustomization: Ye,
    dimension1: P,
    previewMode: h,
    lineCurve: ha,
    showLegendsInColumns: Je == !0 || Je == "true",
    numberOfLegendColumns: parseInt(ga) || 4
  }, ie = {}, le = k(Lt) || {};
  le && le.forEach && le.forEach((e) => {
    e.value != null && e.value.filter((r) => r != null && r.toString().trim() != "").length > 0 && (ie[e.param] = e.value);
  }), ge && (ie.dvzProxyDatasetId = ge);
  let C = null, M = null;
  if (o === "csv")
    C = nr;
  else
    switch (B) {
      case "line":
        C = Z.LineDataFrame;
        break;
      case "pie":
        C = Z.PieDataFrame;
        break;
      case "radar":
        C = Z.BarDataFrame;
        break;
      default:
        C = Z.BarDataFrame;
        break;
    }
  let I = !1;
  switch (B) {
    case "bar":
      M = ar, I = o != "csv" && P == "none" && w.length == 0;
      break;
    case "line":
      M = rr, I = o !== "csv" && (w.length === 0 || P === "none");
      break;
    case "pie":
      I = o != "csv" && w.length == 0, M = er;
      break;
    case "radar":
      I = o != "csv" && w.length == 0, M = tr;
      break;
    default:
      M = /* @__PURE__ */ p("div", { children: "No Chart" });
      break;
  }
  const Sa = ut === "true", N = [];
  P != "none" && N.push(P), be != "none" && N.push(be);
  const [at, Ha] = V(0), [xr, Wa] = V(rt());
  function rt() {
    var e;
    return ((e = window.screen.orientation) == null ? void 0 : e.type) || (window.innerWidth > window.innerHeight ? "landscape-primary" : "portrait-primary");
  }
  return me(() => {
    const e = setTimeout(() => {
      ae && (() => {
        const n = W.current.querySelector(
          ".legends.container.has-standard-12-font-size.bottom"
        ) || W.current.querySelector(
          ".legends.container.items-section:not(.legends.container.top .items-section)"
        );
        if (!n || n.closest(".legends.container.top")) return;
        const { clientHeight: m } = n, z = window.getComputedStyle(n), Ya = parseInt(z.marginTop), ot = parseInt(z.marginBottom), qa = parseInt(z.paddingTop), Ja = parseInt(z.paddingBottom), _a = m + Ya + ot + qa + Ja, nt = n.closest(
          ".ui.fluid.container.content"
        );
        if (nt) {
          const x = nt.querySelector(".data-source");
          if (x) {
            const D = x.getBoundingClientRect(), A = n.getBoundingClientRect();
            if (A.bottom !== 0 && D.top !== 0) {
              if (n.textContent.trim() === "") return;
              const _ = ot, K = A.bottom + _, ce = window.getComputedStyle(x), Q = parseFloat(ce.marginTop) || 0, R = D.top - Q;
              if (K > R) {
                let F = K - R;
                F < 5 && (F += 1), x.style.marginTop = `${F + 1}px`;
              }
            } else
              setTimeout(() => {
                D.top < A.bottom && (x.style.marginTop = `${A.bottom - D.top + 1}px`);
              }, 1e3);
          }
        }
        const de = n.closest(".chart.container");
        if (de) {
          const x = de.getBoundingClientRect(), D = window.getComputedStyle(de), A = Number.parseFloat(D.marginBottom) || 0, _ = x.bottom + A, K = n.getBoundingClientRect(), ce = Number.parseFloat(z.marginTop) || 0, Q = K.top - ce;
          if (Q < _) {
            const R = _ - Q, F = 200, Ka = Math.min(R + 1, F);
            R > 0 && R < F && (n.style.marginTop = `${Ka}px`);
          }
        }
        Ha(_a);
      })();
    }, 100);
    return () => {
      clearTimeout(e);
    };
  }, [ae, W]), me(() => {
    const e = () => {
      setTimeout(() => {
        Wa(rt());
      }, 100);
    };
    return window.screen.orientation ? window.screen.orientation.addEventListener("change", e) : window.addEventListener("resize", e), () => {
      window.screen.orientation ? window.screen.orientation.removeEventListener("change", e) : window.removeEventListener("resize", e);
    };
  }, []), /* @__PURE__ */ p("div", { ref: W, children: /* @__PURE__ */ ue(
    pe,
    {
      className: "chart container",
      style: {
        minHeight: B === "pie" && window.innerWidth <= 480 ? `${parseInt(X) + parseInt(at) * 0.5}px` : `${parseInt(X) + parseInt(at)}px`
      },
      fluid: !0,
      children: [
        /* @__PURE__ */ p(
          Za,
          {
            editing: i,
            style: { height: `${Y}px` },
            params: ie,
            waitForFilters: pa === "true",
            app: o,
            group: fe,
            csv: ht,
            store: [o, O, ...N],
            source: N.join("/"),
            children: /* @__PURE__ */ ue(
              pe,
              {
                style: { height: `${Y}px` },
                className: "body",
                fluid: !0,
                children: [
                  I && /* @__PURE__ */ p(st, { editing: i }),
                  !I && /* @__PURE__ */ ue(Oa, { children: [
                    /* @__PURE__ */ p(st, { app: o, group: fe, noDataMsg: It, children: " " }),
                    /* @__PURE__ */ p(
                      C,
                      {
                        locale: Ke,
                        colorBy: E,
                        hiddenBars: St,
                        swap: U === "true" || U === !0,
                        type: B,
                        includeTotal: !0,
                        includeOverall: Ce === !0 || Ce === "true",
                        overallLabel: te,
                        measures: w,
                        dimensions: [...N],
                        sort: $e,
                        sortReverse: S === !0 || S === "true",
                        sortSecondDimension: Se,
                        sortReverseSecondDimension: H === !0 || H === "true",
                        customLabels: Oe(),
                        children: /* @__PURE__ */ p(
                          sr,
                          {
                            type: B,
                            app: o,
                            locale: Ke,
                            overallLabel: te,
                            customLabels: Oe(),
                            manualColors: Ta(),
                            colorBy: E,
                            scheme: j,
                            barColor: tt.barColor,
                            children: /* @__PURE__ */ p(M, { ...tt })
                          }
                        )
                      }
                    )
                  ] })
                ]
              }
            )
          }
        ),
        /* @__PURE__ */ p("br", {}),
        Sa && L && Pa === "info" && /* @__PURE__ */ p(
          pe,
          {
            fluid: !0,
            style: { height: Y + "px" },
            className: "body",
            children: /* @__PURE__ */ p(or, { post: { content: { rendered: L } } })
          }
        )
      ]
    }
  ) });
}, cr = (v, he) => {
  const { "data-app": i, "data-group": O } = he, L = v.getIn(["data", "measures", i, O]), G = v.getIn(["data", "pageModuleProps"]), l = {};
  return L && Object.keys(L).length > 0 && (l.injectedMeasures = L ?? {}), G && (l.pageModuleProps = G), l;
}, ur = {}, Gr = ir(cr, ur)(lr(dr));
export {
  Gr as default
};
