/**
 * Returns a safe numeric value.
 *
 * @param {number|string} value
 *   The input value.
 *
 * @return {number}
 *   The parsed number or zero.
 */
export function toNumber(value) {
  const numericValue = Number(value);

  return Number.isFinite(numericValue) ? numericValue : 0;
}

/**
 * Returns a chart palette based on the semantic card color.
 *
 * @param {string} colorName
 *   The semantic color name.
 *
 * @return {{line: string, fill: string}}
 *   The chart palette definition.
 */
export function getChartPalette(colorName = "blue") {
  const palette = {
    blue: {
      line: "#69a7f5",
      fill: "rgba(105, 167, 245, 0.18)",
    },
    orange: {
      line: "#e6a23c",
      fill: "rgba(230, 162, 60, 0.18)",
    },
    red: {
      line: "#e07a5f",
      fill: "rgba(224, 122, 95, 0.18)",
    },
    green: {
      line: "#69c17d",
      fill: "rgba(105, 193, 125, 0.18)",
    },
  };

  return palette[colorName] || palette.blue;
}

/**
 * Builds a multiline tooltip string from a chart series.
 *
 * @param {Array} series
 *   The chart series items.
 * @param {string} unit
 *   The optional metric unit.
 *
 * @return {string}
 *   The tooltip string.
 */
export function buildSeriesTooltip(series, unit = "") {
  if (!Array.isArray(series) || !series.length) {
    return "";
  }

  return series
    .map((item) => {
      const label = item.label || "";
      const value = item.value ?? 0;

      return `${label}: ${value}${unit}`;
    })
    .join("\n");
}
