"use strict";
var import_LineChart = require("../LineChart.css");
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const jsxRuntime = require("react/jsx-runtime");
const React = require("react");
const reactVirtuoso = require("react-virtuoso");
const kit_internal_functions = require("./internal/functions.cjs");
const kit_internal_ScaleSelect = require("./internal/ScaleSelect.cjs");
const kit_internal_types = require("./internal/types.cjs");
const kit_internal_UPlot_UPlotChart = require("./internal/UPlot/UPlotChart.cjs");
const kit_internal_UPlot_UPlotChart_closestPointPlugin = require("./internal/UPlot/UPlotChart/closestPointPlugin.cjs");
const kit_internal_UPlot_UPlotChart_tooltipsPlugin = require("./internal/UPlot/UPlotChart/tooltipsPlugin.cjs");
const kit_LineChart_SyncProvider = require("./LineChart/SyncProvider.cjs");
const kit_LineChart_XAxisFilter = require("./LineChart/XAxisFilter.cjs");
const kit_Message = require("./Message.cjs");
const kit_Row = require("./Row.cjs");
const kit_Spinner = require("./Spinner.cjs");
const kit_Surface = require("./Surface.cjs");
const kit_Theme_UI = require("./Theme/UI.cjs");
require("./Theme/themeUtils.cjs");
require("./Theme/themes.cjs");
const kit_utils_loadable = require("./utils/loadable.cjs");
const gridBase = "LineChart_gridBase_7f6d0";
const filterContainer = "LineChart_filterContainer_7f6d0";
const gridContainer = "LineChart_gridContainer_7f6d0";
const gridItem = "LineChart_gridItem_7f6d0";
const chartTitle = "LineChart_chartTitle_7f6d0";
const css = {
  gridBase,
  filterContainer,
  gridContainer,
  gridItem,
  chartTitle
};
const TRAINING_SERIES_COLOR = "#009BDE";
const VALIDATION_SERIES_COLOR = "#F77B21";
const getScientificNotationTickValues = (_self, rawValues) => {
  const useNotation = !!rawValues.find(
    (val) => val > 9999 || val < -9999 || 0 < val && val < 1e-4 || -1e-4 < val && val < 0
  );
  return useNotation ? rawValues.map((val) => val ? val.toExponential(2) : val) : rawValues.map((val) => val ? Number(val.toFixed(2)) : val);
};
const LineChart = ({
  focusedSeries,
  handleError,
  height = 350,
  optionKey,
  onPointClick,
  onPointFocus,
  scale = kit_internal_types.Scale.Linear,
  plugins: propPlugins,
  series: propSeries,
  showLegend = false,
  title,
  xAxis = kit_internal_types.XAxisDomain.Batches,
  xLabel,
  xRange,
  yLabel,
  yTickValues = getScientificNotationTickValues
}) => {
  const series = kit_utils_loadable.Loadable.ensureLoadable(propSeries).getOrElse([]);
  const isLoading = kit_utils_loadable.Loadable.isLoadable(propSeries) && kit_utils_loadable.Loadable.isNotLoaded(propSeries);
  const hasPopulatedSeries = React.useMemo(
    () => !!series.find((serie) => {
      var _a;
      return (_a = serie.data[xAxis]) == null ? void 0 : _a.length;
    }),
    [series, xAxis]
  );
  const seriesColors = React.useMemo(
    () => series.map((s, i) => s.color ?? kit_internal_functions.glasbeyColor(i)),
    [series]
  );
  const chartData = React.useMemo(() => {
    var _a, _b;
    const xSet = /* @__PURE__ */ new Set();
    const yValues = {};
    const xMin = (_a = xRange == null ? void 0 : xRange[xAxis]) == null ? void 0 : _a[0];
    const xMax = (_b = xRange == null ? void 0 : xRange[xAxis]) == null ? void 0 : _b[1];
    if (xMin !== void 0 && xMax !== void 0) {
      xSet.add(xMin);
      xSet.add(xMax);
    }
    series.forEach((serie, serieIndex) => {
      yValues[serieIndex] = {};
      (serie.data[xAxis] || []).forEach((pt) => {
        const xVal = pt[0];
        if (xMin !== void 0 && xVal < xMin || xMax !== void 0 && xVal > xMax) {
          return;
        }
        xSet.add(xVal);
        yValues[serieIndex][xVal] = Number.isFinite(pt[1]) ? pt[1] : null;
      });
    });
    const xValues = Array.from(xSet);
    xValues.sort((a, b) => a - b);
    const yValuesArray = Object.values(yValues).map((yValue) => {
      return xValues.map((xValue) => yValue[xValue] != null ? yValue[xValue] : null);
    });
    return [xValues, ...yValuesArray];
  }, [series, xAxis, xRange]);
  const xTickValues = React.useMemo(() => {
    if (xAxis === kit_internal_types.XAxisDomain.Time) {
      const timeRange = xRange == null ? void 0 : xRange[kit_internal_types.XAxisDomain.Time];
      const timeDelta = timeRange ? (timeRange[1] || 0) - (timeRange[0] || 0) : chartData[0][chartData[0].length - 1] - chartData[0][0];
      if (timeDelta < 43200) {
        return kit_internal_functions.getTimeTickValues;
      }
    }
  }, [chartData, xAxis, xRange]);
  const chartOptions = React.useMemo(() => {
    const plugins = propPlugins ?? [
      kit_internal_UPlot_UPlotChart_tooltipsPlugin.tooltipsPlugin({
        closeOnMouseExit: true,
        isShownEmptyVal: false,
        // use specified color on Serie, or glasbeyColor
        seriesColors
      }),
      kit_internal_UPlot_UPlotChart_closestPointPlugin.closestPointPlugin({
        onPointClick,
        onPointFocus,
        yScale: "y"
      })
    ];
    return {
      axes: [
        {
          font: "12px Inter, Arial, Helvetica, sans-serif, system-ui",
          grid: { show: false },
          incrs: xAxis === kit_internal_types.XAxisDomain.Time ? void 0 : [
            /* eslint-disable array-element-newline */
            1,
            2,
            3,
            4,
            5,
            10,
            25,
            50,
            100,
            250,
            500,
            1e3,
            2500,
            5e3,
            1e4,
            25e3,
            5e4,
            1e5,
            25e4,
            5e5,
            1e6,
            25e5,
            5e6
            /* eslint-enable array-element-newline */
          ],
          label: xLabel,
          scale: "x",
          side: 2,
          space: 120,
          ticks: { show: false },
          values: xTickValues
        },
        {
          font: "12px Inter, Arial, Helvetica, sans-serif, system-ui",
          grid: { stroke: "#E3E3E3", width: 1 },
          label: yLabel,
          labelGap: 8,
          scale: "y",
          side: 3,
          size: 55,
          ticks: { show: false },
          values: yTickValues
        }
      ],
      cursor: {
        drag: { x: true, y: false }
      },
      height: height - (hasPopulatedSeries ? 0 : 20),
      key: optionKey,
      legend: { live: false, show: showLegend },
      plugins,
      scales: {
        x: {
          range: (_, min, max) => {
            var _a, _b;
            const r = (xRange == null ? void 0 : xRange[xAxis]) ? [
              Math.max(min, ((_a = xRange == null ? void 0 : xRange[xAxis]) == null ? void 0 : _a[0]) ?? min),
              Math.min(max, ((_b = xRange == null ? void 0 : xRange[xAxis]) == null ? void 0 : _b[1]) ?? max)
            ] : [min, max];
            return r;
          },
          time: xAxis === kit_internal_types.XAxisDomain.Time
        },
        y: {
          distr: scale === kit_internal_types.Scale.Log ? 3 : 1
        }
      },
      series: [
        { label: xLabel ?? xAxis ?? "X" },
        ...series.map((serie, idx) => {
          return {
            alpha: focusedSeries === void 0 || focusedSeries === idx ? 1 : 0.4,
            label: serie.name,
            points: { show: (serie.data[xAxis] || []).length <= 1 },
            scale: "y",
            spanGaps: true,
            stroke: seriesColors[idx],
            type: "line",
            width: 2
          };
        })
      ]
    };
  }, [
    seriesColors,
    onPointClick,
    onPointFocus,
    xLabel,
    xTickValues,
    yLabel,
    yTickValues,
    height,
    xAxis,
    xRange,
    scale,
    series,
    hasPopulatedSeries,
    propPlugins,
    focusedSeries,
    optionKey,
    showLegend
  ]);
  return /* @__PURE__ */ jsxRuntime.jsxs(kit_Surface, { children: [
    title && /* @__PURE__ */ jsxRuntime.jsx("h5", { className: css.chartTitle, children: title }),
    /* @__PURE__ */ jsxRuntime.jsx(
      kit_internal_UPlot_UPlotChart,
      {
        allowDownload: hasPopulatedSeries,
        data: chartData,
        handleError,
        isLoading,
        options: chartOptions,
        xAxis
      }
    )
  ] });
};
const ChartGrid = React.memo(
  ({
    chartsProps: propChartsProps,
    xAxis,
    onXAxisChange,
    scale,
    setScale,
    handleError
  }) => {
    const {
      themeSettings: { className: themeClass }
    } = kit_Theme_UI.useTheme();
    const scrollingContainer = React.useRef(null);
    const classes = [css.gridBase, themeClass];
    const chartsProps = kit_utils_loadable.Loadable.ensureLoadable(propChartsProps).getOrElse([]).filter(
      (c) => (
        // filter out Loadable series which are Loaded yet have no serie with more than 0 points.
        !kit_utils_loadable.Loadable.isLoadable(c.series) || !kit_utils_loadable.Loadable.isLoaded(c.series) || kit_utils_loadable.Loadable.getOrElse([], c.series).find(
          (serie) => Object.entries(serie.data).find(([, points]) => points.length > 0)
        )
      )
    );
    const isLoading = kit_utils_loadable.Loadable.isLoadable(propChartsProps) && kit_utils_loadable.Loadable.isNotLoaded(propChartsProps);
    const xAxisOptions = React.useMemo(() => {
      const xOpts = /* @__PURE__ */ new Set();
      chartsProps.forEach((chart) => {
        const series = kit_utils_loadable.Loadable.ensureLoadable(chart.series).getOrElse([]);
        series.forEach((serie) => {
          Object.entries(serie.data).forEach(([xAxisOption, dataPoints]) => {
            if (dataPoints.length > 0) {
              xOpts.add(xAxisOption);
            }
          });
        });
      });
      return Array.from(xOpts).sort();
    }, [chartsProps]);
    if (chartsProps.length === 0 && !isLoading)
      return /* @__PURE__ */ jsxRuntime.jsx(kit_Message, { icon: "warning", title: "No data available." });
    return /* @__PURE__ */ jsxRuntime.jsx("div", { className: classes.join(" "), ref: scrollingContainer, children: /* @__PURE__ */ jsxRuntime.jsx(kit_Spinner, { center: true, spinning: isLoading, tip: "Loading chart data...", children: chartsProps.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
      /* @__PURE__ */ jsxRuntime.jsx("div", { className: css.filterContainer, children: /* @__PURE__ */ jsxRuntime.jsxs(kit_Row.Row, { gap: 16, justifyContent: "end", children: [
        /* @__PURE__ */ jsxRuntime.jsx(kit_internal_ScaleSelect, { value: scale, onChange: setScale }),
        xAxisOptions && xAxisOptions.length > 1 && /* @__PURE__ */ jsxRuntime.jsx(kit_LineChart_XAxisFilter, { options: xAxisOptions, value: xAxis, onChange: onXAxisChange })
      ] }) }),
      /* @__PURE__ */ jsxRuntime.jsx(kit_LineChart_SyncProvider.SyncProvider, { children: /* @__PURE__ */ jsxRuntime.jsx(
        reactVirtuoso.VirtuosoGrid,
        {
          customScrollParent: scrollingContainer.current || void 0,
          data: chartsProps,
          itemClassName: css.gridItem,
          itemContent: (i, chartProps) => /* @__PURE__ */ jsxRuntime.jsx(
            LineChart,
            {
              ...chartProps,
              handleError,
              scale,
              xAxis
            },
            i
          ),
          listClassName: css.gridContainer
        }
      ) })
    ] }) }) });
  }
);
exports.ChartGrid = ChartGrid;
exports.LineChart = LineChart;
exports.TRAINING_SERIES_COLOR = TRAINING_SERIES_COLOR;
exports.VALIDATION_SERIES_COLOR = VALIDATION_SERIES_COLOR;
exports.default = LineChart;
