/* Copyright © 2020 Splunk Inc.
SPLUNK CONFIDENTIAL – Use or disclosure of this material in whole or
in part without a valid written license from Splunk Inc. is PROHIBITED. */
import {
  TooltipContainer,
  TooltipOutsideChart
} from "./chunk-ZTIQPCUC.js";
import {
  useCursorPlugin
} from "./chunk-5RMFCCVG.js";
import {
  getFormattedDataColumns
} from "./chunk-XJ2QF2ND.js";
import {
  useDimensions
} from "./chunk-DYC7NOL7.js";
import {
  EventAnnotationContainer
} from "./chunk-BI5HQSM3.js";
import {
  uPlot_min_exports,
  uplot_react_default,
  uplot_react_exports
} from "./chunk-FUNDGA5O.js";
import {
  SideLegend
} from "./chunk-JVJFBB3Y.js";
import {
  themes_exports,
  useVizTheme
} from "./chunk-P6Y5CKTH.js";
import {
  MarksContainer
} from "./chunk-VCBGETN3.js";
import {
  PinContainer
} from "./chunk-SWCBFGHQ.js";
import {
  RangeSelection
} from "./chunk-YOT4BRQD.js";
import {
  styled_components_default,
  styled_components_exports
} from "./chunk-5LUILIR3.js";
import {
  DAY,
  exists,
  getXAxisResolution,
  isNumber,
  isTimeSeriesData,
  mapDSToScales,
  mapDSToSeries,
  mapScalesToAxes,
  markPrefix,
  some_default,
  some_exports,
  stackData,
  uplot_default,
  uplot_exports,
  useCreateAttachedDivElement,
  useDynamicCallback
} from "./chunk-6N4JNZ5S.js";
import {
  lodash_exports
} from "./chunk-FWZM3EJJ.js";
import {
  react_default,
  react_exports
} from "./chunk-V3S5WUKN.js";
import {
  __export,
  __objRest,
  __reExport,
  __spreadProps,
  __spreadValues
} from "./chunk-XC4WXK3L.js";

// esm-externals:react-dom
var react_dom_exports = {};
__export(react_dom_exports, {
  default: () => react_dom_default
});
__reExport(react_dom_exports, react_dom_star);
import * as defaultImport from "react-dom";
import * as react_dom_star from "react-dom";
var react_dom_default = "default" in defaultImport ? defaultImport.default : defaultImport;

// esm-externals:@splunk/react-ui/WaitSpinner
var WaitSpinner_exports = {};
__export(WaitSpinner_exports, {
  default: () => WaitSpinner_default
});
__reExport(WaitSpinner_exports, WaitSpinner_star);
import * as defaultImport2 from "@splunk/react-ui/WaitSpinner";
import * as WaitSpinner_star from "@splunk/react-ui/WaitSpinner";
var WaitSpinner_default = "default" in defaultImport2 ? defaultImport2.default : defaultImport2;

// src/TimeSeriesChart.styled.tsx
var tooltipOutsideChartContainerHeightRaw = 16;
var tooltipOutsideChartContainerHeight = `${tooltipOutsideChartContainerHeightRaw}px`;
var StyledTooltipOutsideChartWrapper = styled_components_default.div`
    height: ${tooltipOutsideChartContainerHeight};
    margin-left: 6px; // Align tooltip container with chart title
`;
var StyledTimeseriesChartContainer = styled_components_default.div`
    height: ${(props) => typeof props.height === "number" ? `${props.height}px` : props.height};
    width: ${(props) => typeof props.width === "number" ? `${props.width}px` : props.width};
`;
var StyledTimeSeriesChart = styled_components_default.div`
    ${({ flexDirection, theme, width }) => `
        flex-direction: ${flexDirection};
        width: ${typeof width === "number" ? `${width}px` : `${width}`};
        --tooltip-line-stroke: ${theme.tooltip.lineStroke};
    `}
    display: flex;
    flex: 1;
    font-family: 'Splunk Data Sans', Arial, sans-serif;
    position: relative;
    height: 100%;

    .olly-viz-nonInteractive {
        position: absolute;
        pointer-events: none;
    }

    .olly-viz-interactive {
        position: absolute;
        pointer-events: none;
    }

    .olly-viz-cursor {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
    }

    .olly-viz-event-annotation:hover {
        scale: 1.1;
    }

    /* Overwrite uplot style */
    .uplot {
        position: relative;
    }

    .u-select {
        background: rgba(0, 0, 0, 0.3);
    }

    .u-hz .u-cursor-x {
        border-right: 1px solid var(--tooltip-line-stroke);
    }

    /* Pin related style */
    ${({ theme }) => `
        --pin-dot-fill: ${theme.pin.dotFill};
        --pin-line-stroke: ${theme.pin.lineStroke};
        --pin-icon-stroke: ${theme.pin.iconStroke};
    `}

    .pin {
        overflow: visible !important;
        pointer-events: none;

        .pin-line {
            stroke: var(--pin-line-stroke);
            stroke-width: 1px;
        }

        .pin-dot-outer {
            fill: var(--pin-dot-fill);
            opacity: 0.4;
        }

        .pin-dot-inner {
            fill: var(--pin-dot-fill);
            cursor: pointer;
            pointer-events: all;

            &.disabled {
                cursor: crosshair;
            }
        }

        .pin-close-line {
            stroke: var(--pin-icon-stroke);
            stroke-width: 1px;
        }
    }
`;

// src/providers/RangeSelectionProvider.tsx
var RangeSelectionProviderContext = (0, react_exports.createContext)(
  void 0
);
var RangeSelectionProvider = ({ children }) => {
  const [rangeSelection, setRangeSelection] = (0, react_exports.useState)();
  return /* @__PURE__ */ react_default.createElement(RangeSelectionProviderContext.Provider, { value: { rangeSelection, setRangeSelection } }, children);
};
var useRangeSelection = () => (0, react_exports.useContext)(RangeSelectionProviderContext);

// src/providers/VizContextProvider.tsx
var VizContext = (0, react_exports.createContext)(null);
var VizContextProvider = ({ children }) => {
  const [syncedHoverValue, setSyncedHoverValue] = (0, react_exports.useState)();
  const [syncedSelectedValue, setSyncedSelectedValue] = (0, react_exports.useState)();
  const clearSharedState = (0, react_exports.useCallback)(() => {
    setSyncedHoverValue(void 0);
    setSyncedSelectedValue(void 0);
  }, []);
  const props = (0, react_exports.useMemo)(
    () => ({
      clearSharedState,
      syncedHoverValue,
      setSyncedHoverValue,
      syncedSelectedValue,
      setSyncedSelectedValue
    }),
    [clearSharedState, syncedHoverValue, syncedSelectedValue]
  );
  return /* @__PURE__ */ react_default.createElement(VizContext.Provider, { value: props }, children);
};

// src/providers/useVizContext.ts
var useVizContext = () => {
  const [syncedHoverValue, setSyncedHoverValue] = (0, react_exports.useState)();
  const [syncedSelectedValue, setSyncedSelectedValue] = (0, react_exports.useState)();
  const clearSharedState = (0, react_exports.useCallback)(() => {
    setSyncedHoverValue(void 0);
    setSyncedSelectedValue(void 0);
  }, []);
  const vizSyncContext = (0, react_exports.useContext)(VizContext);
  if (vizSyncContext !== null) {
    return __spreadProps(__spreadValues({}, vizSyncContext), { hasProvider: true });
  }
  return {
    clearSharedState,
    syncedHoverValue,
    setSyncedHoverValue,
    syncedSelectedValue,
    setSyncedSelectedValue,
    hasProvider: false
  };
};

// esm-externals:debug
var debug_exports = {};
__export(debug_exports, {
  default: () => debug_default
});
__reExport(debug_exports, debug_star);
import * as defaultImport3 from "debug";
import * as debug_star from "debug";
var debug_default = "default" in defaultImport3 ? defaultImport3.default : defaultImport3;

// esm-externals:lodash/isEqual
var isEqual_exports = {};
__export(isEqual_exports, {
  default: () => isEqual_default
});
__reExport(isEqual_exports, isEqual_star);
import * as defaultImport4 from "lodash/isEqual";
import * as isEqual_star from "lodash/isEqual";
var isEqual_default = "default" in defaultImport4 ? defaultImport4.default : defaultImport4;

// esm-externals:lodash/isFunction
var isFunction_exports = {};
__export(isFunction_exports, {
  default: () => isFunction_default
});
__reExport(isFunction_exports, isFunction_star);
import * as defaultImport5 from "lodash/isFunction";
import * as isFunction_star from "lodash/isFunction";
var isFunction_default = "default" in defaultImport5 ? defaultImport5.default : defaultImport5;

// src/utilities/useMemoGuaranteed.ts
var useMemoGuaranteed = (factory, deps) => {
  const prevDepsRef = (0, react_exports.useRef)(void 0);
  const prevValueRef = (0, react_exports.useRef)(void 0);
  if (!prevDepsRef.current || prevDepsRef.current.length !== deps.length || !prevDepsRef.current.every((prevDep, i) => prevDep === deps[i])) {
    prevValueRef.current = factory(prevValueRef.current);
    prevDepsRef.current = deps;
  }
  return prevValueRef.current;
};

// src/renderers/uplot.tsx
var log = (0, debug_exports.debug)("olly-timeseries-viz:uplot");
var FOCUS_MAX_SERIES = 30;
var UPlotRenderComponent = (props) => {
  var _a;
  const locale = props.userLocale;
  const { rawXaxisValues, timestampFormat } = props;
  const { fields, columns: dataColumns } = props.data;
  const isTimeSeries = isTimeSeriesData(props.data);
  const columns = [
    dataColumns[0],
    ...getFormattedDataColumns(props.data, props.seriesConfig, props.scaleConfig)
  ];
  const xAxisResolution = (0, react_exports.useMemo)(() => getXAxisResolution(props.data), [props.data]);
  const series = (0, react_exports.useMemo)(
    () => mapDSToSeries(fields, props.seriesConfig, props.scaleConfig, props.hiddenSeries),
    [fields, props.scaleConfig, props.seriesConfig, props.hiddenSeries]
  );
  const shouldLimitHoverDistance = (0, react_exports.useMemo)(
    () => some_default(props.seriesConfig, (v) => exists(v.type) && v.type === "stacked-bar"),
    [props.seriesConfig]
  );
  const scales = (0, react_exports.useMemo)(
    () => mapDSToScales(props.seriesConfig, props.scaleConfig, props.range, isTimeSeries),
    [props.range, props.scaleConfig, props.seriesConfig, isTimeSeries]
  );
  const axes = (0, react_exports.useMemo)(
    () => mapScalesToAxes(
      xAxisResolution,
      props.theme,
      props.scaleConfig,
      locale,
      props.hideXAxis,
      props.range,
      isTimeSeries,
      rawXaxisValues,
      timestampFormat
    ),
    [
      xAxisResolution,
      props.theme,
      props.scaleConfig,
      props.hideXAxis,
      locale,
      props.range,
      isTimeSeries,
      rawXaxisValues,
      timestampFormat
    ]
  );
  const { data: alignedData, bands } = useMemoGuaranteed(
    (previous) => {
      const output = stackData(series, columns);
      if (isEqual_default(output.bands, previous == null ? void 0 : previous.bands)) {
        return { data: output.data, bands: previous == null ? void 0 : previous.bands };
      }
      return output;
    },
    [columns, series]
  );
  const maxSeriesFocus = (_a = props.maxSeriesFocus) != null ? _a : FOCUS_MAX_SERIES;
  const opts = (0, react_exports.useMemo)(() => {
    log("Setting up new uPlot Object");
    let destroyed = false;
    return {
      width: 0,
      height: 0,
      series,
      bands,
      tzDate: (ts) => uplot_default.tzDate(new Date(ts * 1e3), locale.tz),
      plugins: [
        {
          hooks: {
            // The "setSize" event will
            setSize: props.onReady,
            setCursor: props.onSetCursor,
            setSeries: props.onSetSeries,
            drawAxes: (
              // Always draw x-axis line
              (u) => {
                if (destroyed) {
                  return;
                }
                const xLft = u.bbox.left;
                const xRgt = u.bbox.left + u.bbox.width;
                const yBtm = u.bbox.top + u.bbox.height;
                u.ctx.save();
                u.ctx.beginPath();
                u.ctx.strokeStyle = props.theme.axis.axisStroke;
                u.ctx.lineWidth = 2;
                u.ctx.moveTo(xLft, yBtm);
                u.ctx.lineTo(xRgt, yBtm);
                u.ctx.stroke();
                u.ctx.restore();
              }
            ),
            draw: (u) => {
              if (destroyed) {
                return;
              }
              const rootRect = u.root.getBoundingClientRect();
              const overRect = u.over.getBoundingClientRect();
              function align(el) {
                el.style.top = `${overRect.top - rootRect.top}px`;
                el.style.left = `${overRect.left - rootRect.left}px`;
                el.style.width = `${overRect.width}px`;
                el.style.height = `${overRect.height}px`;
              }
              if (props.interactiveEl) {
                align(props.interactiveEl);
              }
            },
            destroy: () => {
              log("uPlot Object destroyed");
              destroyed = true;
            }
          }
        }
      ],
      cursor: {
        x: false,
        y: false,
        focus: series.length > maxSeriesFocus + 1 ? { show: false, prox: 0 } : { prox: 1e3 },
        hover: {
          prox: shouldLimitHoverDistance ? 50 : 1e3,
          bias: 0
        },
        drag: {
          setScale: false,
          x: false,
          y: false
        }
      },
      pxAlign: true,
      scales,
      axes,
      legend: { show: false },
      padding: timestampFormat === "expanded" ? [10, 52, 20, 10] : void 0
      // For multi-line format x-axis labels
    };
  }, [
    series,
    bands,
    props.onReady,
    props.onSetCursor,
    props.onSetSeries,
    props.theme.axis.axisStroke,
    props.interactiveEl,
    shouldLimitHoverDistance,
    scales,
    axes,
    locale,
    maxSeriesFocus,
    timestampFormat
  ]);
  const { height, width } = props;
  const options = (0, react_exports.useMemo)(
    () => __spreadProps(__spreadValues({}, opts), {
      width,
      height,
      series
    }),
    [height, opts, series, width]
  );
  return /* @__PURE__ */ react_default.createElement(uplot_react_default, { options, data: alignedData });
};
var uPlotPlotRendererFactory = (options) => {
  let uPlotRef;
  function getUplotColorAsString(fillOrStroke, i) {
    if (!uPlotRef || !fillOrStroke) {
      return void 0;
    }
    if (isFunction_default(fillOrStroke)) {
      const fillResponse = fillOrStroke(uPlotRef, i);
      if (fillResponse === null) {
        return void 0;
      }
      return String(fillResponse);
    }
    return String(fillOrStroke);
  }
  const utils = () => !uPlotRef ? void 0 : {
    dimensions: {
      root: uPlotRef.root.getBoundingClientRect(),
      over: uPlotRef.over.getBoundingClientRect()
    },
    valToPos: (value, scaleKey) => (uPlotRef == null ? void 0 : uPlotRef.valToPos(value, scaleKey)) || 0,
    posToVal: (value, scaleKey) => (uPlotRef == null ? void 0 : uPlotRef.posToVal(value, scaleKey)) || 0,
    setCursor: (cursor, fire = false) => {
      uPlotRef == null ? void 0 : uPlotRef.setCursor(cursor, fire);
    },
    setFocusedSeries: (field) => {
      if (field === null) {
        uPlotRef == null ? void 0 : uPlotRef.setSeries(null, { focus: true }, false);
      } else {
        const seriesIdx = (uPlotRef == null ? void 0 : uPlotRef.series).findIndex(
          (s) => s.key === field
        );
        uPlotRef == null ? void 0 : uPlotRef.setSeries(seriesIdx, { focus: true }, false);
      }
    },
    allSeries: uPlotRef.series.map((s, i) => ({
      field: s.key,
      label: s.label,
      fill: getUplotColorAsString(s.fill, i),
      stroke: getUplotColorAsString(s.stroke, i),
      show: s.show || false
    })),
    el: uPlotRef.root
  };
  const onSetCursorListeners = [];
  const fireSetCursorListeners = (u) => {
    onSetCursorListeners.forEach((fn) => {
      if (!u.cursor || u.cursor.idx === null) {
        fn(null);
      } else {
        fn({
          top: isNumber(u.cursor.top) ? u.cursor.top : -10,
          left: isNumber(u.cursor.left) ? u.cursor.left : -10,
          index: isNumber(u.cursor.idx) ? u.cursor.idx : -10
        });
      }
    });
  };
  const onFocusSeriesListeners = [];
  const fireFocusSeriesListeners = (u, seriesIndex) => {
    onFocusSeriesListeners.forEach((fn) => {
      fn(seriesIndex);
    });
  };
  function onReady(u) {
    var _a;
    uPlotRef = u;
    (_a = options.onReady) == null ? void 0 : _a.call(options, utils, uPlotRef);
  }
  return {
    utils,
    renderer: {
      onSetCursor: (fn) => {
        onSetCursorListeners.push(fn);
      },
      onFocusSeries: (fn) => {
        onFocusSeriesListeners.push(fn);
      },
      component: (props) => /* @__PURE__ */ react_default.createElement(
        UPlotRenderComponent,
        __spreadProps(__spreadValues({}, props), {
          onReady,
          onSetCursor: fireSetCursorListeners,
          onSetSeries: fireFocusSeriesListeners
        })
      )
    }
  };
};
var useUplotPlotRendererFactory = (onReady) => {
  const [, updateState] = react_default.useState();
  const forceUpdate = react_default.useCallback(() => updateState({}), []);
  const [ref] = (0, react_exports.useState)(
    () => uPlotPlotRendererFactory({
      onReady: (utils, uplotRef) => {
        onReady == null ? void 0 : onReady(utils, uplotRef);
        forceUpdate();
      }
    })
  );
  return ref;
};

// src/TimeSeriesChart.tsx
var EPOCH_SECONDS_MAX_VALUE = Date.now() / 100;
var globalId = 0;
var useSharedInteractions = (vizId, loading) => {
  var _b;
  const isInteractionOrigin = (0, react_exports.useRef)({
    selection: false,
    hover: false,
    range: false
  });
  const _a = useVizContext(), {
    syncedHoverValue,
    syncedSelectedValue,
    setSyncedSelectedValue,
    setSyncedHoverValue
  } = _a, restVizContext = __objRest(_a, [
    "syncedHoverValue",
    "syncedSelectedValue",
    "setSyncedSelectedValue",
    "setSyncedHoverValue"
  ]);
  const rangeSelectionOutput = useRangeSelection();
  isInteractionOrigin.current = {
    selection: (syncedSelectedValue == null ? void 0 : syncedSelectedValue.originViz) === vizId,
    hover: (syncedHoverValue == null ? void 0 : syncedHoverValue.originViz) === vizId,
    range: ((_b = rangeSelectionOutput == null ? void 0 : rangeSelectionOutput.rangeSelection) == null ? void 0 : _b.vizId) === vizId
  };
  (0, react_exports.useEffect)(() => {
    var _a2;
    if (rangeSelectionOutput !== void 0) {
      isInteractionOrigin.current.range = ((_a2 = rangeSelectionOutput.rangeSelection) == null ? void 0 : _a2.vizId) === vizId;
    } else {
      isInteractionOrigin.current.range = false;
    }
  }, [rangeSelectionOutput, isInteractionOrigin, vizId]);
  const setRangeSelection = rangeSelectionOutput == null ? void 0 : rangeSelectionOutput.setRangeSelection;
  const clearSelectionsFromCurrent = (0, react_exports.useCallback)(() => {
    if (isInteractionOrigin.current.selection) {
      setSyncedSelectedValue(void 0);
    }
    if (isInteractionOrigin.current.hover) {
      setSyncedHoverValue(void 0);
    }
    if (isInteractionOrigin.current.range && setRangeSelection) {
      setRangeSelection(void 0);
    }
  }, [isInteractionOrigin, setSyncedSelectedValue, setSyncedHoverValue, setRangeSelection]);
  (0, react_exports.useEffect)(() => {
    if (loading) {
      clearSelectionsFromCurrent();
    }
  }, [clearSelectionsFromCurrent, loading]);
  (0, react_exports.useEffect)(
    () => () => {
      clearSelectionsFromCurrent();
    },
    // On unmount, clear shared state
    [clearSelectionsFromCurrent]
  );
  return __spreadProps(__spreadValues({}, restVizContext), {
    syncedHoverValue,
    syncedSelectedValue,
    setSyncedSelectedValue,
    setSyncedHoverValue,
    isInteractionOrigin,
    rangeSelection: rangeSelectionOutput == null ? void 0 : rangeSelectionOutput.rangeSelection,
    setRangeSelection: rangeSelectionOutput == null ? void 0 : rangeSelectionOutput.setRangeSelection
  });
};
var normalizeTimeValue = (val) => {
  if (typeof val === "string") {
    return Date.parse(val) / 1e3;
  }
  if (typeof val === "number" && val > EPOCH_SECONDS_MAX_VALUE) {
    return val / 1e3;
  }
  return val;
};
var WaitSpinnerWrapper = (props) => /* @__PURE__ */ react_default.createElement(
  "div",
  {
    style: {
      width: "100%",
      height: "100%",
      display: "flex",
      justifyContent: "center",
      alignItems: "center"
    }
  },
  props.children
);
var defaultTz = Intl.DateTimeFormat().resolvedOptions().timeZone;
var DEFAULT_LOCALE = {
  tz: defaultTz,
  twelveHourTimeFormat: true
};
var InternalTimeSeriesChart = (props) => {
  var _a, _b, _c, _d;
  const theme = useVizTheme();
  const [id] = (0, react_exports.useState)(() => {
    globalId += 1;
    return `${props.id || globalId}`;
  });
  const localeInfo = (props == null ? void 0 : props.userLocale) || DEFAULT_LOCALE;
  const { utils: plotUtilitiesFn, renderer: plotRenderer } = useUplotPlotRendererFactory(props == null ? void 0 : props.onReady);
  const plotUtilities = plotUtilitiesFn();
  const dailyAxisResolution = ((_a = props.range) == null ? void 0 : _a.dailyResolution) ? DAY : void 0;
  const xResolution = (0, react_exports.useMemo)(
    () => dailyAxisResolution || getXAxisResolution(props.data),
    [props.data, dailyAxisResolution]
  );
  const timestampFormat = (props == null ? void 0 : props.timestampFormat) || "compact";
  const cursorEl = useCreateAttachedDivElement(plotUtilities == null ? void 0 : plotUtilities.el, "olly-viz-cursor");
  const interactiveEl = useCreateAttachedDivElement(plotUtilities == null ? void 0 : plotUtilities.el, "olly-viz-interactive");
  const markEl = useCreateAttachedDivElement(interactiveEl, "olly-viz-marks");
  const eventAnnotationEl = useCreateAttachedDivElement(interactiveEl, "olly-viz-eventAnnotations");
  const pinEl = useCreateAttachedDivElement(interactiveEl, "olly-viz-pin");
  const rangeEl = useCreateAttachedDivElement(interactiveEl, "olly-viz-range");
  const tooltipEl = useCreateAttachedDivElement(interactiveEl, "olly-viz-tooltip");
  const { width: containerWidth, height: containerHeight } = props;
  const {
    ref: containerRef,
    dimensions: { width, height }
  } = useDimensions();
  const {
    syncedHoverValue,
    setSyncedHoverValue,
    syncedSelectedValue,
    setSyncedSelectedValue,
    rangeSelection,
    setRangeSelection,
    hasProvider
  } = useSharedInteractions(id, props.loading);
  const {
    onRangeSelection: unstableOnRangeSelection,
    onRangeZoom: unstableOnRangeZoom,
    hideTooltipSeriesLabel
  } = props;
  const onRangeZoom = useDynamicCallback(unstableOnRangeZoom);
  const handleRangeSelectionChange = (0, react_exports.useCallback)(
    (range, e) => {
      if (setRangeSelection) {
        setRangeSelection(range);
      }
      if (setSyncedSelectedValue) {
        setSyncedSelectedValue(void 0);
      }
      if (unstableOnRangeSelection) {
        unstableOnRangeSelection(range, e);
      }
    },
    [unstableOnRangeSelection, setRangeSelection, setSyncedSelectedValue]
  );
  const onRangeSelection = useDynamicCallback(handleRangeSelectionChange);
  const {
    data: rawData,
    onCrosshairClick: onCrosshairClickFromProps,
    onCrosshairChange: onCrosshairChangeFromProps
  } = props;
  const isTimeSeries = isTimeSeriesData(rawData);
  const rawXaxisValues = props.data.columns[0];
  const [data, timeWindow] = (0, react_exports.useMemo)(() => {
    const normalizedData = {
      fields: rawData.fields,
      columns: rawData.columns.slice(0)
    };
    let dataPoints = normalizedData.columns[0];
    if (!dataPoints || dataPoints.length === 0) {
      return [normalizedData];
    }
    if (isTimeSeries && (typeof dataPoints[0] === "string" || typeof dataPoints[0] === "number" && dataPoints[0] > EPOCH_SECONDS_MAX_VALUE)) {
      normalizedData.columns[0] = dataPoints.map(normalizeTimeValue);
    }
    if (!isTimeSeries) {
      normalizedData.columns[0] = dataPoints.map((v, idx) => idx);
    }
    dataPoints = normalizedData.columns[0];
    return [
      normalizedData,
      [Number(dataPoints[0]) || -1, Number(dataPoints[dataPoints.length - 1]) || -1]
    ];
  }, [rawData, isTimeSeries]);
  const { seriesConfig, scaleConfig, onSeriesClick, legend: legendOriginal } = props;
  const getDataOnClick = (0, react_exports.useCallback)(
    (seriesIndex, dataIdx, dataSet) => {
      var _a2;
      return seriesIndex !== void 0 && dataIdx !== void 0 ? (_a2 = dataSet.columns[seriesIndex][dataIdx]) != null ? _a2 : 0 : 0;
    },
    []
  );
  const handleSelectedStateChange = (0, react_exports.useCallback)(
    (event) => {
      if (event && (event == null ? void 0 : event.time) && (event == null ? void 0 : event.seriesIndex) && (event == null ? void 0 : event.seriesKey)) {
        setSyncedSelectedValue({
          originViz: id,
          xVal: event.time,
          seriesKey: event.seriesKey
        });
        if (setRangeSelection) {
          setRangeSelection(void 0);
        }
        if (onCrosshairClickFromProps) {
          const value = getDataOnClick(event.seriesIndex, event.index, data);
          onCrosshairClickFromProps(__spreadProps(__spreadValues({}, event), { xResolution, value }));
        }
      }
    },
    [
      setSyncedSelectedValue,
      id,
      setRangeSelection,
      onCrosshairClickFromProps,
      getDataOnClick,
      data,
      xResolution
    ]
  );
  const handleHoverStateChange = (0, react_exports.useCallback)(
    (crosshairValue2) => {
      if (hasProvider) {
        setSyncedHoverValue(
          (crosshairValue2 == null ? void 0 : crosshairValue2.time) ? {
            originViz: id,
            xVal: crosshairValue2.time,
            seriesKey: crosshairValue2.seriesKey
          } : void 0
        );
      }
      if (onCrosshairChangeFromProps) {
        onCrosshairChangeFromProps();
      }
    },
    [id, setSyncedHoverValue, onCrosshairChangeFromProps, hasProvider]
  );
  const crosshairValue = (0, react_exports.useMemo)(
    () => (syncedHoverValue == null ? void 0 : syncedHoverValue.xVal) ? { time: syncedHoverValue.xVal } : void 0,
    [syncedHoverValue]
  );
  const onCrosshairChange = handleHoverStateChange;
  const onCrosshairClick = useDynamicCallback(handleSelectedStateChange);
  const { cursorState } = useCursorPlugin({
    id,
    plotUtilitiesFn,
    plotRenderer,
    cursorEl,
    crosshairValue,
    onCrosshairChange,
    onCrosshairClick,
    onRangeSelection
  });
  const [eventAnnotationCursorState, setEventAnnotationCursorState] = (0, react_exports.useState)();
  const onEventAnnotationClick = useDynamicCallback((_b = props.eventsConfig) == null ? void 0 : _b.onEventAnnotationClick);
  const handleClosePin = () => {
    var _a2;
    setSyncedSelectedValue == null ? void 0 : setSyncedSelectedValue(void 0);
    (_a2 = props.onPinClose) == null ? void 0 : _a2.call(props);
  };
  const onPinClose = useDynamicCallback(handleClosePin);
  const events = (0, react_exports.useMemo)(
    () => {
      var _a2;
      return (_a2 = props.events) == null ? void 0 : _a2.map((event) => __spreadProps(__spreadValues({}, event), {
        time: normalizeTimeValue(event.time)
      }));
    },
    [props.events]
  );
  const pinValue = (0, react_exports.useMemo)(() => {
    const { xVal, seriesKey, originViz } = syncedSelectedValue || {};
    if (!xVal || !seriesKey || !timeWindow) {
      return void 0;
    }
    const [start, end] = timeWindow;
    const isWithinTimeWindow = start <= xVal && xVal <= end;
    return isWithinTimeWindow ? {
      time: xVal,
      isActive: originViz === id
    } : void 0;
  }, [id, syncedSelectedValue, timeWindow]);
  const [hiddenSeries, setHiddenSeries] = (0, react_exports.useState)([]);
  const updateSeriesVisibility = (0, react_exports.useCallback)(
    (field) => setHiddenSeries((currentlyHidden) => (0, lodash_exports.xor)(currentlyHidden, [field])),
    []
  );
  const [selectedField, setSelectedField] = (0, react_exports.useState)(null);
  (0, react_exports.useEffect)(() => {
    plotUtilities == null ? void 0 : plotUtilities.setFocusedSeries(selectedField);
  }, [selectedField]);
  const { legend, legendSize, legendAnchor } = (0, react_exports.useMemo)(() => {
    if (legendOriginal === false) {
      return { legend: null };
    }
    const _legend = exists(legendOriginal) ? legendOriginal : SideLegend;
    return {
      legend: react_default.createElement(_legend.component, {
        cursorState,
        plotUtilities,
        data,
        seriesConfig,
        scaleConfig,
        marks: props.marks,
        onSeriesClick: (field, ref) => {
          if (props.legendClickTogglesSeriesVisibility) {
            updateSeriesVisibility(field);
          } else {
            onSeriesClick == null ? void 0 : onSeriesClick(field, ref);
          }
        },
        onSeriesHover: setSelectedField
      }),
      legendSize: _legend.size,
      legendAnchor: _legend.anchor
    };
  }, [
    legendOriginal,
    plotUtilities,
    cursorState,
    data,
    seriesConfig,
    scaleConfig,
    props.marks,
    onSeriesClick,
    props.legendClickTogglesSeriesVisibility,
    updateSeriesVisibility
  ]);
  if (props.loading || !((_c = data == null ? void 0 : data.columns) == null ? void 0 : _c.length)) {
    return /* @__PURE__ */ react_default.createElement(WaitSpinnerWrapper, null, /* @__PURE__ */ react_default.createElement(WaitSpinner_default, null));
  }
  const tooltipOutsideChartHeight = props.showTooltipOutsideChart ? tooltipOutsideChartContainerHeightRaw : 0;
  const plotRendererWidth = legend && legendAnchor === "right" ? width - ((legendSize == null ? void 0 : legendSize.width) || 0) : width;
  const plotRendererHeight = legend && legendAnchor === "bottom" ? height - ((legendSize == null ? void 0 : legendSize.height) || 0) - tooltipOutsideChartHeight : height - tooltipOutsideChartHeight;
  return /* @__PURE__ */ react_default.createElement(
    StyledTimeseriesChartContainer,
    {
      "data-testid": id,
      ref: containerRef,
      className: "TimeSeriesChart-root",
      height: containerHeight,
      width: containerWidth
    },
    props.showTooltipOutsideChart && /* @__PURE__ */ react_default.createElement(StyledTooltipOutsideChartWrapper, { "data-test": "tooltip-outside-chart-container" }, /* @__PURE__ */ react_default.createElement(
      TooltipOutsideChart,
      {
        plotUtilities,
        cursorState,
        data,
        userLocale: localeInfo,
        seriesConfig: props.seriesConfig,
        scaleConfig: props.scaleConfig,
        eventAnnotationCursorState
      }
    )),
    /* @__PURE__ */ react_default.createElement(
      StyledTimeSeriesChart,
      {
        flexDirection: legend && legendAnchor === "right" ? "row" : "column",
        theme,
        width: containerWidth
      },
      width > 0 && height > 0 ? /* @__PURE__ */ react_default.createElement("div", { style: { position: "relative", width: containerWidth } }, /* @__PURE__ */ react_default.createElement(
        plotRenderer.component,
        {
          width: plotRendererWidth,
          height: plotRendererHeight,
          data,
          seriesConfig: props.seriesConfig,
          scaleConfig: props.scaleConfig,
          hideXAxis: props.hideXAxis,
          interactiveEl,
          theme,
          range: props.range,
          hiddenSeries,
          userLocale: localeInfo,
          maxSeriesFocus: props.maxSeriesFocus,
          rawXaxisValues,
          timestampFormat
        }
      )) : null,
      legend ? /* @__PURE__ */ react_default.createElement("div", { className: "viz-legend" }, legend) : null,
      tooltipEl && cursorState ? react_dom_default.createPortal(
        /* @__PURE__ */ react_default.createElement(
          TooltipContainer,
          {
            plotUtilities,
            tooltip: props.tooltip,
            cursorState,
            data,
            seriesConfig: props.seriesConfig,
            scaleConfig: props.scaleConfig,
            eventAnnotationCursorState,
            eventAnnotationConfig: props.eventsConfig,
            eventAnnotationTooltip: (_d = props.eventsConfig) == null ? void 0 : _d.tooltip,
            chartTitle: props.title,
            xAxisResolution: dailyAxisResolution,
            userLocale: localeInfo,
            hideTooltipSeriesLabel,
            showTooltipOutsideChart: props.showTooltipOutsideChart,
            isTimeSeries,
            rawXaxisValues
          }
        ),
        tooltipEl
      ) : null,
      markEl ? react_dom_default.createPortal(
        /* @__PURE__ */ react_default.createElement(
          MarksContainer,
          {
            plotUtilities,
            marks: props.marks,
            selectedMark: (selectedField == null ? void 0 : selectedField.startsWith(markPrefix)) ? selectedField : void 0
          }
        ),
        markEl
      ) : null,
      rangeEl && props.onRangeSelection ? react_dom_default.createPortal(
        /* @__PURE__ */ react_default.createElement(
          RangeSelection,
          {
            plotUtilities,
            cursorState,
            rangeSelection: (rangeSelection == null ? void 0 : rangeSelection.vizId) === id ? rangeSelection : void 0,
            onRangeDeselection: (e) => handleRangeSelectionChange == null ? void 0 : handleRangeSelectionChange(void 0, e),
            onRangeZoom
          }
        ),
        rangeEl
      ) : null,
      eventAnnotationEl ? react_dom_default.createPortal(
        /* @__PURE__ */ react_default.createElement(
          EventAnnotationContainer,
          {
            events,
            eventAnnotationConfig: props.eventsConfig,
            plotUtilities,
            onEventAnnotationHover: (event) => {
              var _a2, _b2;
              (_b2 = (_a2 = props.eventsConfig) == null ? void 0 : _a2.onEventAnnotationHover) == null ? void 0 : _b2.call(_a2, event == null ? void 0 : event.time);
              setEventAnnotationCursorState(event);
            },
            onEventAnnotationClick,
            xResolution
          }
        ),
        eventAnnotationEl
      ) : null,
      pinEl ? react_dom_default.createPortal(
        /* @__PURE__ */ react_default.createElement(
          PinContainer,
          {
            plotUtilities,
            data,
            pinValue,
            onPinClose
          }
        ),
        pinEl
      ) : null
    )
  );
};
var TimeSeriesChart = (_a) => {
  var _b = _a, { theme } = _b, props = __objRest(_b, ["theme"]);
  if (!theme) {
    return /* @__PURE__ */ react_default.createElement(InternalTimeSeriesChart, __spreadValues({}, props));
  }
  return /* @__PURE__ */ react_default.createElement(themes_exports.SplunkThemeProvider, { colorScheme: theme }, /* @__PURE__ */ react_default.createElement(InternalTimeSeriesChart, __spreadValues({}, props)));
};

export {
  RangeSelectionProvider,
  useRangeSelection,
  VizContextProvider,
  useVizContext,
  TimeSeriesChart
};
//# sourceMappingURL=chunk-ZUJYGCUD.js.map
