import { jsxs as v, jsx as s, Fragment as Y } from "react/jsx-runtime";
import { useState as k, useEffect as it, Fragment as ct } from "react";
import { injectIntl as ot } from "react-intl";
import { ResponsiveLine as mt } from "@nivo/line";
import dt from "./Tooltip.js";
import { area as ht, line as ft } from "d3-shape";
import { useTheme as ut } from "@nivo/theming";
import pt from "../../layout/FlexWrapDetector.js";
import K from "../../utils/deviceType.js";
const xt = "#66676d", J = "#f0f0f1", ge = ["mobile", "tablet", "midTablet"].includes(K()), be = K() === "mobile", ve = ["tablet", "midTablet"].includes(K()), yt = (m, x) => {
  const E = document.createElement("canvas").getContext("2d");
  return E.font = x, E.measureText(m).width;
}, gt = ({
  editing: m,
  previewMode: x,
  app: Z,
  legends: E,
  tooltip: $,
  tooltipEnabled: Ee,
  options: d,
  intl: I,
  groupMode: q,
  reverse: bt,
  marginLeft: Ne,
  lineLabelPosition: Oe,
  marginTop: Q,
  marginRight: Te,
  marginBottom: X,
  format: N,
  colors: vt,
  offsetY: Me,
  height: De,
  showLegends: P,
  legendPosition: h,
  tickRotation: y,
  offsetText: A,
  tickColor: B,
  legendLabel: C,
  xLabelColor: O,
  colorGenerator: ee,
  legendCheckBack: j,
  legendLabelBack: ke,
  legendLabelColor: te,
  highlightXAxisLine: $e,
  showTickLine: S,
  showRightAxis: Ie,
  valueScale: Et,
  enableArea: Le,
  areaShadingCriteria: ae,
  areaLowerBound: re,
  areaUpperBound: ne,
  showPoints: Fe,
  maxValue: We,
  fixedMinValue: H,
  fixedMaxValue: R,
  offsetBottom: we,
  yAxisTickValues: ze,
  enableGridY: _e,
  enableGridX: Ae,
  overrideTickColor: U,
  offsetRight: Be,
  selectedMeasures: je,
  tooltipEnableMarkdown: Se,
  minMaxClamp: He,
  reverseLegend: Re,
  customAxisFormat: L,
  mobileCustomization: Ue,
  lineCurve: Ge,
  customLabels: G,
  lineXAxisTickMode: se,
  lineXAxisTickCount: Ve,
  lineXAxisTickEvery: Ye
}) => {
  var pe, xe, ye;
  const i = JSON.parse(decodeURIComponent(Ue)), le = ge && ((i == null ? void 0 : i.showCustomization) ?? !1), F = le && x !== "Desktop", W = !m && le, [ie, Je] = k(50), [ce, Ke] = k(Q), [Nt, oe] = k(0), [me, Ze] = k(X), [T, qe] = k([]), w = d.data.map((e) => ({
    id: e.id,
    label: G && G[e.id] ? G[e.id] : e.label || e.id,
    color: ee.getColor(e.id, e)
  })), de = () => (Re && w.reverse(), /* @__PURE__ */ s(Y, { children: P && w.map((e, a) => /* @__PURE__ */ v("div", { className: "legend item", onClick: () => Pe(e.id), children: [
    /* @__PURE__ */ s(
      "input",
      {
        className: "ignore",
        type: "checkbox",
        checked: T.length === 0 || !T.includes(e.id),
        readOnly: !0,
        style: {
          backgroundColor: j === !0 ? e.color : "none",
          color: te
        }
      }
    ),
    /* @__PURE__ */ s(
      "span",
      {
        className: j === !0 ? "checkmark-with-bg" : "checkmark",
        style: {
          backgroundColor: j === !0 ? e.color : "transparent"
        }
      }
    ),
    /* @__PURE__ */ s(
      "label",
      {
        style: {
          backgroundColor: ke === !0 ? e.color : "transparent",
          color: te
        },
        children: e.label
      }
    )
  ] }, a)) }));
  it(() => {
    (() => {
      const l = 5 * Math.max(w.length - 5, 0);
      Je(l);
    })();
  }, [w]);
  const Qe = {
    bottom: `-${ie}px`
  }, Xe = {
    bottom: `-${ie}px`,
    gap: "0px",
    top: "0px"
  }, z = (e) => T.length ? e.filter((a) => T.indexOf(a.id) === -1) : e, Pe = (e) => {
    const a = T.slice();
    if (a.indexOf(e) > -1) {
      const l = a.indexOf(e);
      a.splice(l, 1);
    } else
      a.push(e);
    qe(a);
  }, Ce = (e) => {
    const a = Object.assign({}, e), l = ut();
    (F || W) && fe.includes(String(a.value)) && (a.value = "");
    let t = [], r = "";
    if (F || W) {
      const c = String(a.value).split(" ");
      let o = 25;
      m && x === "Mobile" || be && !m ? o = (i == null ? void 0 : i.mobileMaxTickLength) ?? 25 : m && x === "Tablet" || ve && !m ? o = (i == null ? void 0 : i.tabletMaxTickLength) ?? 25 : window.matchMedia("(min-width: 768px) and (max-width: 1250px)").matches && !m && (o = 15), c.forEach((g) => {
        r.length + String(g).length <= o ? r += (r ? " " : "") + g : (t.push(r), r = g);
      }), r && t.push(r);
    } else
      t = [a.value];
    let n = 12;
    return m && x === "Mobile" || be && !m ? n = (i == null ? void 0 : i.mobileYAxisLineHeight) ?? 12 : (m && x === "Tablet" || ve && !m) && (n = (i == null ? void 0 : i.tabletYAxisLineHeight) ?? 12), yt(a.value, "12px Roboto") + 15, y > 0 && y < 180 ? /* @__PURE__ */ v("g", { transform: `translate(${e.x},${e.y + 30})`, children: [
      S && /* @__PURE__ */ s(
        "line",
        {
          stroke: U ? B : J,
          strokeWidth: 1.5,
          y1: -32,
          y2: -12
        }
      ),
      /* @__PURE__ */ s("g", { transform: `translate(0, ${e.y + A})`, children: t.map((c, o) => /* @__PURE__ */ s(
        "text",
        {
          transform: `rotate(${y})`,
          textAnchor: "start",
          y: typeof e.value == "number" ? 0 : o * n,
          dominantBaseline: "middle",
          style: {
            ...l.axis.ticks.text,
            fill: O === "null" ? "black" : O,
            fontSize: "12px",
            fontFamily: "sans-serif"
          },
          children: c
        },
        c
      )) })
    ] }) : y > 180 && y < 360 ? /* @__PURE__ */ v("g", { transform: `translate(${e.x},${e.y + 30})`, children: [
      S && /* @__PURE__ */ s(
        "line",
        {
          stroke: U ? B : J,
          strokeWidth: 1.5,
          y1: -32,
          y2: -12
        }
      ),
      /* @__PURE__ */ s("g", { transform: `translate(0, ${e.y + A})`, children: /* @__PURE__ */ s(
        "text",
        {
          transform: `rotate(${y})`,
          textAnchor: "end",
          dominantBaseline: "middle",
          style: {
            ...l.axis.ticks.text,
            fill: O,
            fontSize: "12px"
          },
          children: a.value
        }
      ) })
    ] }) : /* @__PURE__ */ v("g", { transform: `translate(${e.x},${e.y + 30})`, children: [
      S && /* @__PURE__ */ s(
        "line",
        {
          stroke: U ? B : J,
          strokeWidth: 1.5,
          y1: -32,
          y2: -12
        }
      ),
      /* @__PURE__ */ s("g", { transform: `translate(0, ${e.y + A})`, children: t.map((c, o) => /* @__PURE__ */ s(
        "text",
        {
          transform: `rotate(${y})`,
          textAnchor: "middle",
          y: typeof e.value == "number" ? 0 : o * n,
          dominantBaseline: "middle",
          style: {
            ...l.axis.ticks.text,
            fill: O === "null" ? "black" : O,
            fontSize: "12px",
            fontFamily: "sans-serif"
          },
          children: c
        },
        c
      )) })
    ] });
  }, et = ({ series: e, xScale: a, yScale: l, innerHeight: t }) => {
    const r = e && e.length > 0 ? e[0].color : "#3daff7", n = [];
    e[0] && e[0].data.forEach((p) => {
      Z == "csv" ? d.keys.forEach((b) => {
        n.push({ measure: b, min: p.data.variables[b] });
      }) : je.forEach((b) => {
        n.push({ measure: b, min: p.data.variables[b] });
      });
    });
    const c = n.sort((p, b) => p.min - b.min), o = ae == "CUSTOM_BETWEEN_TWO_LINES" && re ? re : c[0].measure, g = ae == "CUSTOM_BETWEEN_TWO_LINES" && ne ? ne : c[c.length - 1].measure, lt = ht().x((p) => a(p.data.x)).y0((p) => l(p.data.variables[o])).y1((p) => l(p.data.variables[g]));
    return /* @__PURE__ */ s(Y, { children: e && e[0] && /* @__PURE__ */ s(
      "path",
      {
        d: lt(e[0].data),
        fill: r,
        fillOpacity: 0.4
      }
    ) });
  }, tt = ({ series: e, xScale: a, yScale: l, innerHeight: t, innerWidth: r }) => {
    const n = [0, r], c = ft().x((o, g) => g === 0 ? -10 : o).y((o) => l(0));
    return /* @__PURE__ */ s(ct, { children: /* @__PURE__ */ s(
      "path",
      {
        d: c(n),
        fill: "none",
        stroke: xt,
        style: { pointerEvents: "none", strokeDasharray: "4 4" }
      }
    ) });
  }, M = ["grid", "axes", "lines", "legends"];
  Le && M.push(et), Fe && (M.push("points"), M.push("mesh")), $e && M.push(tt);
  let D = [];
  z(d.data).forEach((e) => {
    e.data && (D = [...D, ...e.data.map((a) => a.y)]);
  });
  const at = () => {
    if (q === "stacked") {
      const e = [];
      z(d.data).forEach((t) => {
        e.push(...t.data);
      });
      const l = [];
      e.forEach((t) => {
        l.indexOf(t.x) == -1 && l.push(t.x);
      }), u = Math.max(
        ...l.map((t) => e.filter((r) => r.x == t).map((r) => r.y).reduce((r, n) => Math.max(r + n, r + 0)))
      ), f = Math.min(
        ...l.map((t) => e.filter((r) => r.x == t).map((r) => r.y).reduce((r, n) => Math.min(r - n, n - r)))
      );
    } else
      D.length > 0 && (u = Math.max(...D), f = Math.min(...D));
    return u = u < 0 ? u * 0.9 : u * 1.1, f = f > 0 ? f * 0.9 : f * 1.1, { min: f, max: u };
  };
  let f = "auto", u = "auto";
  const _ = at();
  We == "fixed" ? (f = H != null && H != "" ? H : _.min, u = R != null && R != "" ? R : _.max) : (f = _.min, u = _.max);
  const he = () => /* @__PURE__ */ s(Y, { children: P && C && /* @__PURE__ */ s("div", { className: "legend item", children: /* @__PURE__ */ s("label", { className: "legend-title", children: C }) }) }), rt = {
    top: ce,
    right: Te,
    bottom: me,
    left: Ne
  };
  let V = parseInt(ze);
  const nt = d.data && ((xe = (pe = d.data) == null ? void 0 : pe.filter((e) => {
    var a;
    return ((a = e == null ? void 0 : e.data) == null ? void 0 : a.length) > 0;
  })) == null ? void 0 : xe.length), fe = [];
  if (F || W) {
    V = Number.parseInt(i.yAxisTickValues);
    const e = new Map(Object.entries(((ye = i == null ? void 0 : i.labels) == null ? void 0 : ye.xAxis) ?? {}));
    for (const [a, l] of e)
      l || fe.push(a);
  }
  const ue = z(d.data), st = ["grid", "axes", "legends"];
  if (d != null && d.data && nt > 0) {
    let e = z(d.data);
    const a = [];
    e.forEach((t) => {
      t && Array.isArray(t.data) && t.data.forEach((r) => {
        const n = r && r.x;
        n !== void 0 && a.indexOf(n) === -1 && a.push(n);
      });
    });
    let l;
    if (se === "count") {
      const t = Math.max(1, parseInt(Ve));
      if (a.length > 0 && t > 0)
        if (a.length <= t)
          l = a.slice();
        else {
          const r = (a.length - 1) / (t - 1), n = new Array(t);
          for (let c = 0; c < t; c++)
            n[c] = Math.floor(c * r);
          n[t - 1] = a.length - 1, l = n.map((c) => a[c]);
        }
    } else if (se === "every") {
      const t = Math.max(1, parseInt(Ye));
      if (a.length > 0) {
        const r = [];
        for (let n = 0; n < a.length; n++)
          n % t === 0 && r.push(a[n]);
        r[r.length - 1] !== a[a.length - 1] && r.push(a[a.length - 1]), l = r;
      }
    }
    return /* @__PURE__ */ v("div", { style: { height: De }, children: [
      /* @__PURE__ */ s(
        mt,
        {
          curve: Ge,
          data: ue,
          margin: rt,
          xScale: { type: "point" },
          yScale: {
            type: "linear",
            min: f,
            max: u,
            stacked: q == "stacked",
            reverse: !1,
            clamp: He
          },
          layers: ue.length === 0 ? st : M,
          axisTop: null,
          axisRight: Ie ? {
            tickSize: 5,
            tickValues: V,
            tickPadding: 5,
            tickRotation: 0,
            legend: E.right,
            legendPosition: "middle",
            legendOffset: parseInt(Be),
            format: (t) => {
              const r = L || N;
              return I.formatNumber(
                r.style === "percent" ? t / 100 : t,
                {
                  ...r
                }
              );
            }
          } : null,
          enableGridY: _e,
          enableGridX: Ae,
          enablePointLabel: Oe === "top",
          pointLabel: (t) => I.formatNumber(
            N.style === "percent" ? t.yFormatted / 100 : t.yFormatted,
            N
          ),
          lineWidth: 3,
          colors: (t) => ee.getColor(t.id, t),
          axisBottom: (F || W) && (i == null ? void 0 : i.xAxisDisabled) === !0 ? null : {
            ...l ? { tickValues: l } : {},
            renderTick: Ce,
            legend: E.bottom,
            legendPosition: "middle",
            legendOffset: Number.parseInt(we)
          },
          axisLeft: {
            tickSize: 5,
            tickValues: V,
            tickPadding: 5,
            tickRotation: 0,
            legend: E.left,
            legendPosition: "middle",
            legendOffset: Number.parseInt(Me),
            format: (t) => {
              const r = L || N;
              return I.formatNumber(
                r.style === "percent" ? t / 100 : t,
                {
                  ...r
                }
              );
            }
          },
          tooltip: (t) => Ee && $ && $.trim().length > 0 ? /* @__PURE__ */ s(
            dt,
            {
              intl: I,
              format: N,
              d: t,
              tooltip: $,
              tooltipEnableMarkdown: Se
            }
          ) : null,
          pointSize: 10,
          pointBorderWidth: 2,
          pointBorderColor: { from: "serieColor" },
          useMesh: e.length > 0 && e[0].data.length > 0
        },
        /* @__PURE__ */ new Date()
      ),
      (h === "top" || h === "bottom") && /* @__PURE__ */ s(
        "div",
        {
          className: `legends container has-standard-12-font-size ${h}`,
          style: h === "top" ? { marginTop: ge && `${ce}px` } : h === "bottom" ? { marginBottom: `${me}px` } : {},
          children: /* @__PURE__ */ v("div", { className: "legend-sections", children: [
            /* @__PURE__ */ s("div", { className: "title-section", children: he() }),
            /* @__PURE__ */ s(
              pt,
              {
                onWrapChange: (t) => {
                  if (h === "top") {
                    const r = Q + t / 2 * 40;
                    Ke(r), oe(t);
                  } else
                    Ze(X + t / 2 * 25), oe(t);
                },
                className: "legends container has-standard-12-font-size items-section",
                children: de()
              }
            )
          ] })
        }
      ),
      (h === "right" || h === "left") && /* @__PURE__ */ v(
        "div",
        {
          className: `legends container has-standard-12-font-size  ${h}`,
          style: h === "right" ? Qe : Xe,
          children: [
            he(),
            de()
          ]
        }
      )
    ] });
  }
  return /* @__PURE__ */ s("div", {});
}, Wt = ot(gt);
export {
  Wt as default
};
