import "../../../../tooltipsPlugin.css";
import { glasbeyColor, humanReadableNumber } from "../../functions.js";
const tooltip = "tooltipsPlugin_tooltip_4d252";
const checkpointHeader = "tooltipsPlugin_checkpointHeader_4d252";
const valueX = "tooltipsPlugin_valueX_4d252";
const valueY = "tooltipsPlugin_valueY_4d252";
const valueYEmpty = "tooltipsPlugin_valueYEmpty_4d252";
const color = "tooltipsPlugin_color_4d252";
const bar = "tooltipsPlugin_bar_4d252";
const css = {
  tooltip,
  checkpointHeader,
  valueX,
  valueY,
  valueYEmpty,
  color,
  bar
};
const tooltipsPlugin = ({
  closeOnMouseExit,
  getXTooltipHeader,
  getXTooltipYLabels,
  isShownEmptyVal,
  seriesColors
} = {
  isShownEmptyVal: true,
  seriesColors: []
}) => {
  let barEl = null;
  let displayedIdx = null;
  let tooltipEl = null;
  const _buildTooltipHtml = (uPlot2, idx) => {
    let html = "";
    const header = typeof getXTooltipHeader === "function" ? getXTooltipHeader(idx) : "";
    const yLabels = typeof getXTooltipYLabels === "function" ? getXTooltipYLabels(idx) : [];
    const xSerie = uPlot2.series[0];
    const xValue = typeof xSerie.value === "function" ? xSerie.value(uPlot2, uPlot2.data[0][idx], 0, idx) : uPlot2.data[0][idx];
    html += `
      <div class="${css.valueX}">
        ${header}
        ${xSerie.label} ${xValue}
      </div>`;
    let minYDist = 1e3;
    const seriesValues = uPlot2.series.map((serie, i) => {
      if (serie.scale === "x" || !serie.show)
        return;
      const label = yLabels[i - 1] || null;
      const valueRaw = uPlot2.data[i][idx];
      const cssClass = valueRaw !== null ? css.valueY : css.valueYEmpty;
      if (isShownEmptyVal || valueRaw || valueRaw === 0) {
        const log = Math.log10(Math.abs(valueRaw || 0));
        const precision = log > -5 ? 6 - Math.max(0, Math.ceil(log)) : void 0;
        const yDist = Math.abs(uPlot2.valToPos(valueRaw || 0, "y") - (uPlot2.cursor.top || 0));
        minYDist = Math.min(minYDist, yDist);
        return {
          html: `
          <div class="${cssClass}">
            <span class="${css.color}" style="background-color: ${seriesColors[i - 1] ?? glasbeyColor(i - 1)}"></span>
            ${label ? label + "<br />" : ""}
            ${serie.label}: ${valueRaw != null ? humanReadableNumber(valueRaw, precision) : "N/A"}
          </div>`,
          val: valueRaw,
          yDist
        };
      }
      return { val: null };
    }).filter((val) => (val == null ? void 0 : val.val) !== null && !!(val == null ? void 0 : val.html));
    html += seriesValues.sort((a, b) => {
      if (!a || !b) {
        return 0;
      }
      if (a.val === null) {
        if (b.val === null) {
          return 0;
        }
        return 1;
      } else if (b.val === null) {
        return -1;
      }
      return (b.val || 0) - (a.val || 0);
    }).map((seriesValue) => {
      if ((seriesValue == null ? void 0 : seriesValue.yDist) === minYDist) {
        return `<strong>${(seriesValue == null ? void 0 : seriesValue.html) || ""}</strong>`;
      }
      return (seriesValue == null ? void 0 : seriesValue.html) || "";
    }).join("");
    return html;
  };
  const _getTooltipLeftPx = (uPlot2, idx) => {
    var _a;
    const margin = 32;
    const idxLeft = uPlot2.valToPos(uPlot2.data[0][idx], "x");
    if (!tooltipEl)
      return idxLeft;
    const chartWidth = (_a = uPlot2.root.querySelector(".u-over")) == null ? void 0 : _a.getBoundingClientRect().width;
    const tooltipWidth = tooltipEl.getBoundingClientRect().width;
    if (chartWidth && idxLeft + tooltipWidth >= chartWidth * 0.9) {
      return Math.max(0, idxLeft - tooltipWidth - margin);
    }
    return idxLeft + margin;
  };
  const _updateTooltipVerticalPosition = (uPlot2, cursorTop) => {
    var _a;
    if (!tooltipEl)
      return;
    const chartHeight = (_a = uPlot2.root.querySelector(".u-over")) == null ? void 0 : _a.getBoundingClientRect().height;
    const vPos = chartHeight && cursorTop > chartHeight / 2 ? "top" : "bottom";
    tooltipEl.style.bottom = vPos === "bottom" ? "0px" : "auto";
    tooltipEl.style.top = vPos === "top" ? "0px" : "auto";
  };
  const showIdx = (uPlot2, idx) => {
    if (!tooltipEl || !barEl)
      return;
    displayedIdx = idx;
    const idxLeft = uPlot2.valToPos(uPlot2.data[0][idx], "x");
    barEl.style.display = "block";
    barEl.style.left = idxLeft + "px";
    tooltipEl.innerHTML = _buildTooltipHtml(uPlot2, idx);
    tooltipEl.style.display = "block";
    tooltipEl.style.left = _getTooltipLeftPx(uPlot2, idx) + "px";
  };
  const hide = () => {
    if (!tooltipEl || !barEl)
      return;
    displayedIdx = null;
    barEl.style.display = "none";
    tooltipEl.style.display = "none";
  };
  return {
    hooks: {
      init: (uPlot2) => {
        uPlot2.over.onmouseenter = (e) => {
          var _a;
          const originElement = e.relatedTarget;
          if (!((_a = originElement == null ? void 0 : originElement.className) == null ? void 0 : _a.includes("tooltip"))) {
            hide();
          }
        };
        if (closeOnMouseExit) {
          uPlot2.over.onmouseout = () => {
            hide();
          };
        }
      },
      ready: (uPlot2) => {
        var _a, _b;
        tooltipEl = document.createElement("div");
        tooltipEl.className = css.tooltip;
        (_a = uPlot2.root.querySelector(".u-over")) == null ? void 0 : _a.appendChild(tooltipEl);
        barEl = document.createElement("div");
        barEl.className = css.bar;
        (_b = uPlot2.root.querySelector(".u-over")) == null ? void 0 : _b.appendChild(barEl);
      },
      setCursor: (uPlot2) => {
        const { left, idx, top } = uPlot2.cursor;
        if (!left || left < 0 || !top || top < 0 || idx == null) {
          hide();
          return;
        }
        const seriesWithXValue = uPlot2.series.find(
          (serie, serieId) => serie.scale !== "x" && serie.show && uPlot2.data[serieId][idx] != null
        );
        if (seriesWithXValue) {
          showIdx(uPlot2, idx);
        } else {
          hide();
        }
        if (displayedIdx) {
          _updateTooltipVerticalPosition(uPlot2, top);
        }
      }
    }
  };
};
export {
  tooltipsPlugin
};
