import { describe, expect, test } from "vitest";
import { HUB_SENTIMENT_VALUES } from "@formbricks/types/feedback-source";
import { EMPTY_GROUP_VALUE } from "@/modules/ee/analysis/charts/lib/chart-series";
import {
  AXIS_LABEL_GAP,
  AXIS_LABEL_LINE_HEIGHT,
  CATEGORY_AXIS_LABEL_LINES,
  CATEGORY_AXIS_MAX_SHARE,
  CATEGORY_AXIS_MIN_CEILING,
  CATEGORY_AXIS_MIN_WIDTH,
  CHART_EMOTION_COLORS,
  CHART_MEASURE_COLORS,
  CHART_NOT_ENRICHED_COLOR,
  CHART_SENTIMENT_COLORS,
  CHART_VALUE_BAND_COLORS,
  PIE_MEASURE_ID_KEY,
  PIE_MEASURE_NAME_KEY,
  PIE_MEASURE_VALUE_KEY,
  PIVOTED_MEASURE_KEY,
  PIVOTED_VALUE_KEY,
  VALUE_LABEL_MAX_PADDING,
  VALUE_LABEL_MIN_PADDING,
  buildDistributionSegments,
  formatCellValue,
  formatPercentShare,
  formatXAxisTick,
  getBandMeasureColor,
  getCategoryAxisWidth,
  getCategoryLabelBoxHeight,
  getCategoryLabelLineClamp,
  getLegendHeight,
  getRotatedAxisHeight,
  getSemanticDimensionColor,
  getSemanticMeasureColor,
  getSentimentMeasureColor,
  getValueLabelPadding,
  pivotMeasuresToCategories,
  prepareMeasureSliceData,
  preparePieData,
  resolveChartType,
  shouldRotateCategoryLabels,
  truncateLabelToBox,
  truncateRotatedLabel,
} from "./chart-utils";

describe("chart-utils", () => {
  describe("prepareMeasureSliceData", () => {
    const label = (k: string) => `L:${k}`;

    test("pivots each measure column into its own slice", () => {
      const rows = [{ "m.joy": 1163, "m.anger": 1050, "m.fear": 3 }];
      const result = prepareMeasureSliceData(rows, ["m.joy", "m.anger", "m.fear"], label);
      expect(result).toEqual([
        {
          [PIE_MEASURE_NAME_KEY]: "L:m.joy",
          [PIE_MEASURE_ID_KEY]: "m.joy",
          [PIE_MEASURE_VALUE_KEY]: 1163,
          tooltipLabel: "L:m.joy",
        },
        {
          [PIE_MEASURE_NAME_KEY]: "L:m.anger",
          [PIE_MEASURE_ID_KEY]: "m.anger",
          [PIE_MEASURE_VALUE_KEY]: 1050,
          tooltipLabel: "L:m.anger",
        },
        {
          [PIE_MEASURE_NAME_KEY]: "L:m.fear",
          [PIE_MEASURE_ID_KEY]: "m.fear",
          [PIE_MEASURE_VALUE_KEY]: 3,
          tooltipLabel: "L:m.fear",
        },
      ]);
    });

    test("carries the response base onto every slice, summed across rows like the measures", () => {
      const rows = [
        { "m.promoterCount": 30, "m.detractorCount": 2, "m.npsCount": 40 },
        { "m.promoterCount": 7, "m.detractorCount": 0, "m.npsCount": 8 },
      ];
      const result = prepareMeasureSliceData(
        rows,
        ["m.promoterCount", "m.detractorCount"],
        label,
        "m.npsCount"
      );
      expect(result.map((row) => row["m.npsCount"])).toEqual([48, 48]);
      expect(prepareMeasureSliceData(rows, ["m.promoterCount"], label)[0]).not.toHaveProperty("m.npsCount");
    });

    // The tooltip labels each row from its dataKey, which for these slices is the internal
    // PIE_MEASURE_VALUE_KEY — without tooltipLabel it renders that raw key (ENG-2346).
    test("labels every slice for the tooltip, never leaving the internal value key exposed", () => {
      const rows = [{ "m.joy": 10, "m.anger": 2 }];
      const result = prepareMeasureSliceData(rows, ["m.joy", "m.anger"], label);
      expect(result.map((row) => row.tooltipLabel)).toEqual(["L:m.joy", "L:m.anger"]);
      expect(result.every((row) => !String(row.tooltipLabel).includes(PIE_MEASURE_VALUE_KEY))).toBe(true);
    });

    test("sums a measure across multiple rows and treats non-numeric as 0", () => {
      const rows = [
        { "m.joy": 10, "m.anger": "x" },
        { "m.joy": 5, "m.anger": 2 },
      ];
      const result = prepareMeasureSliceData(rows, ["m.joy", "m.anger"], label);
      expect(result).toEqual([
        {
          [PIE_MEASURE_NAME_KEY]: "L:m.joy",
          [PIE_MEASURE_ID_KEY]: "m.joy",
          [PIE_MEASURE_VALUE_KEY]: 15,
          tooltipLabel: "L:m.joy",
        },
        {
          [PIE_MEASURE_NAME_KEY]: "L:m.anger",
          [PIE_MEASURE_ID_KEY]: "m.anger",
          [PIE_MEASURE_VALUE_KEY]: 2,
          tooltipLabel: "L:m.anger",
        },
      ]);
    });

    // ENG-2346: the tooltip falls back to formatting a row's dataKey when the row carries no
    // `tooltipLabel`, and the slice value lives under a synthetic key that is not a Cube column —
    // so a missing label surfaced to users as the literal "__measure Value".
    test("carries the translated measure label so the tooltip never formats the synthetic value key", () => {
      const result = prepareMeasureSliceData([{ "m.joy": 236 }], ["m.joy"], label);
      expect(result[0].tooltipLabel).toBe("L:m.joy");
    });
  });

  describe("resolveChartType", () => {
    test("returns valid chart types", () => {
      expect(resolveChartType("area")).toBe("area");
      expect(resolveChartType("bar")).toBe("bar");
      expect(resolveChartType("pie")).toBe("pie");
      expect(resolveChartType("big_number")).toBe("big_number");
    });

    test("maps the retired line type onto area rather than the bar fallback", () => {
      expect(resolveChartType("line")).toBe("area");
    });

    test("defaults to bar for invalid type", () => {
      expect(resolveChartType("invalid")).toBe("bar");
      expect(resolveChartType("")).toBe("bar");
      // An inherited Object key must not resolve through the legacy alias lookup.
      expect(resolveChartType("constructor")).toBe("bar");
    });
  });

  describe("buildDistributionSegments", () => {
    test("sizes each section by its share of the total", () => {
      const result = buildDistributionSegments([
        { key: "a", label: "A", value: 30 },
        { key: "b", label: "B", value: 10 },
      ]);
      expect(result).not.toBeNull();
      expect(result!.total).toBe(40);
      expect(result!.segments.map((s) => s.percent)).toEqual([0.75, 0.25]);
    });

    test("orders sections largest first, the order preparePieData uses", () => {
      const result = buildDistributionSegments([
        { key: "small", label: "Small", value: 1 },
        { key: "big", label: "Big", value: 99 },
      ]);
      expect(result!.segments.map((s) => s.key)).toEqual(["big", "small"]);
    });

    test("keeps the caller's order for equal shares, so the palette handout is stable", () => {
      const result = buildDistributionSegments([
        { key: "a", label: "A", value: 5 },
        { key: "b", label: "B", value: 5 },
        { key: "c", label: "C", value: 5 },
      ]);
      expect(result!.segments.map((s) => s.key)).toEqual(["a", "b", "c"]);
    });

    test("drops non-positive and non-numeric entries from the total", () => {
      const result = buildDistributionSegments([
        { key: "a", label: "A", value: 10 },
        { key: "zero", label: "Zero", value: 0 },
        { key: "negative", label: "Negative", value: -5 },
        { key: "text", label: "Text", value: "n/a" },
        { key: "empty", label: "Empty", value: null },
      ]);
      expect(result!.total).toBe(10);
      expect(result!.segments.map((s) => s.key)).toEqual(["a"]);
    });

    test("returns null when nothing positive is left to show", () => {
      expect(buildDistributionSegments([])).toBeNull();
      expect(buildDistributionSegments([{ key: "a", label: "A", value: 0 }])).toBeNull();
      expect(buildDistributionSegments([{ key: "a", label: "A", value: "text" }])).toBeNull();
    });

    test("keeps semantic colors and hands the palette only to the rest", () => {
      const result = buildDistributionSegments([
        { key: "positive", label: "Positive", value: 5, color: CHART_SENTIMENT_COLORS.positive },
        { key: "other", label: "Other", value: 5 },
        { key: "another", label: "Another", value: 5 },
      ]);
      expect(result!.segments.map((s) => s.color)).toEqual([
        CHART_SENTIMENT_COLORS.positive,
        CHART_MEASURE_COLORS[0],
        CHART_MEASURE_COLORS[1],
      ]);
    });
  });

  describe("preparePieData", () => {
    test("returns null for empty or no valid numeric data", () => {
      expect(preparePieData([], "count")).toBeNull();
      expect(preparePieData([{ label: "A", count: "text" }], "count")).toBeNull();
      expect(preparePieData([{ label: "A", count: null }], "count")).toBeNull();
    });

    test("drops zero-value rows alongside non-numeric ones", () => {
      const data = [
        { sentiment: "positive", count: 10 },
        { sentiment: "neutral", count: 0 },
        { sentiment: "skip", count: "n/a" },
      ];
      const result = preparePieData(data, "count");
      expect(result).not.toBeNull();
      expect(result!.processedData).toHaveLength(1);
      expect(result!.processedData[0].sentiment).toBe("positive");
    });

    test("colours slices from the mixed measure palette for distinguishability", () => {
      const data = [
        { sentiment: "positive", count: 10 },
        { sentiment: "negative", count: 5 },
        { sentiment: "skip", count: "n/a" },
      ];
      const result = preparePieData(data, "count");
      expect(result).not.toBeNull();
      expect(result!.processedData).toHaveLength(2);
      expect(result!.processedData[0].count).toBe(10);
      expect(result!.colors[0]).toBe(CHART_MEASURE_COLORS[0]);
      expect(result!.colors[1]).toBe(CHART_MEASURE_COLORS[1]);
    });

    test("greys the not-enriched slice and colours sentiment slices semantically", () => {
      const nameKey = "FeedbackRecords.sentiment";
      const data = [
        { [nameKey]: "", count: 20 }, // biggest → sorted first → not enriched
        { [nameKey]: "positive", count: 6 },
        { [nameKey]: "negative", count: 4 },
      ];
      const result = preparePieData(data, "count", nameKey);
      expect(result).not.toBeNull();
      // gray for the empty (not-enriched) slice; sentiment slices are keyed by enum value
      expect(result!.colors[0]).toBe(CHART_NOT_ENRICHED_COLOR);
      expect(result!.colors[1]).toBe(CHART_SENTIMENT_COLORS.positive);
      expect(result!.colors[2]).toBe(CHART_SENTIMENT_COLORS.negative);
    });

    test("falls back to the palette for unknown sentiment tokens without letting semantic slices consume hues", () => {
      const nameKey = "FeedbackRecords.sentiment";
      const data = [
        { [nameKey]: "very_positive", count: 9 },
        { [nameKey]: "unexpected_token", count: 5 },
        { [nameKey]: "another_unknown", count: 3 },
      ];
      const result = preparePieData(data, "count", nameKey);
      expect(result).not.toBeNull();
      expect(result!.colors[0]).toBe(CHART_SENTIMENT_COLORS.very_positive);
      // palette indices start at 0 for the non-semantic slices
      expect(result!.colors[1]).toBe(CHART_MEASURE_COLORS[0]);
      expect(result!.colors[2]).toBe(CHART_MEASURE_COLORS[1]);
    });

    test("uses palette colours when no nameKey is provided", () => {
      const data = [{ label: "A", count: 5 }];
      const result = preparePieData(data, "count");
      expect(result!.colors[0]).toBe(CHART_MEASURE_COLORS[0]);
    });
  });

  describe("formatXAxisTick", () => {
    test("returns empty for null/undefined", () => {
      expect(formatXAxisTick(null)).toBe("");
      expect(formatXAxisTick(undefined)).toBe("");
    });

    test("formats ISO date string", () => {
      expect(formatXAxisTick("2024-06-15")).toMatch(/Jun \d+, 2024/);
    });

    test("passes through non-date string", () => {
      expect(formatXAxisTick("hello")).toBe("hello");
    });

    test("formats number as string when it parses as date, else passes through", () => {
      expect(formatXAxisTick(1.5)).toBe("1.5");
    });

    test("does not interpret bare year-shaped strings as dates", () => {
      // parseISO("1000") is a valid year-only ISO date and would render as
      // "Jan 1, 1000" — but a 4-digit numeric category label shouldn't be
      // turned into a date.
      expect(formatXAxisTick("1000")).toBe("1000");
      expect(formatXAxisTick("2024")).toBe("2024");
      expect(formatXAxisTick(1000)).toBe("1000");
    });

    test("returns empty for boolean", () => {
      expect(formatXAxisTick(true)).toBe("");
    });
  });

  describe("formatCellValue", () => {
    test("returns empty for null/undefined", () => {
      expect(formatCellValue(null)).toBe("");
      expect(formatCellValue(undefined)).toBe("");
    });

    test("formats number with locale", () => {
      expect(formatCellValue(1000)).toBe("1,000");
      expect(formatCellValue(3.14)).toBe("3.14");
    });

    test("formats ISO date string", () => {
      expect(formatCellValue("2024-01-15")).toMatch(/Jan \d+, 2024/);
    });

    test("returns string as-is when not date", () => {
      expect(formatCellValue("hello")).toBe("hello");
    });

    test("stringifies object", () => {
      expect(formatCellValue({ a: 1 })).toBe('{"a":1}');
    });

    test("converts boolean and bigint", () => {
      expect(formatCellValue(true)).toBe("true");
      expect(formatCellValue(123n)).toBe("123");
    });
  });

  describe("getSemanticDimensionColor", () => {
    const sentimentDim = "FeedbackRecords.sentiment";

    test("maps every sentiment enum value to its semantic color", () => {
      for (const value of HUB_SENTIMENT_VALUES) {
        expect(getSemanticDimensionColor(sentimentDim, value)).toBe(CHART_SENTIMENT_COLORS[value]);
      }
    });

    test("returns the not-enriched gray for empty enrichment values", () => {
      expect(getSemanticDimensionColor(sentimentDim, "")).toBe(CHART_NOT_ENRICHED_COLOR);
      expect(getSemanticDimensionColor(sentimentDim, null)).toBe(CHART_NOT_ENRICHED_COLOR);
      expect(getSemanticDimensionColor("FeedbackRecords.emotions", "")).toBe(CHART_NOT_ENRICHED_COLOR);
    });

    test("returns undefined for unknown tokens and non-sentiment dimensions", () => {
      expect(getSemanticDimensionColor(sentimentDim, "unexpected_token")).toBeUndefined();
      // a combination of emotions is a group of its own and takes the palette
      expect(getSemanticDimensionColor("FeedbackRecords.emotions", "joy, fear")).toBeUndefined();
      expect(getSemanticDimensionColor("FeedbackRecords.language", "positive")).toBeUndefined();
    });
  });

  test("the shown empty group is gray on every chart type, pies included", () => {
    expect(getSemanticDimensionColor("FeedbackRecords.sourceName", EMPTY_GROUP_VALUE)).toBe(
      CHART_NOT_ENRICHED_COLOR
    );
    expect(getSemanticDimensionColor("FeedbackRecords.sentiment", EMPTY_GROUP_VALUE)).toBe(
      CHART_NOT_ENRICHED_COLOR
    );
  });

  describe("emotion colors", () => {
    test("each emotion keeps one fixed color as a dimension value and as a count measure", () => {
      for (const emotion of ["joy", "surprise", "anger", "sadness", "fear", "disgust"] as const) {
        expect(getSemanticDimensionColor("FeedbackRecords.emotions", emotion)).toBe(
          CHART_EMOTION_COLORS[emotion]
        );
        expect(getSemanticMeasureColor(`FeedbackRecords.${emotion}Count`)).toBe(
          CHART_EMOTION_COLORS[emotion]
        );
      }
      expect(new Set(Object.values(CHART_EMOTION_COLORS)).size).toBe(6);
    });
  });

  describe("red → green scales", () => {
    test("NPS bands and sentiment share the traffic-light steps", () => {
      expect(CHART_VALUE_BAND_COLORS.negative).toBe(CHART_SENTIMENT_COLORS.very_negative);
      expect(CHART_VALUE_BAND_COLORS.neutral).toBe(CHART_SENTIMENT_COLORS.neutral);
      expect(CHART_VALUE_BAND_COLORS.positive).toBe(CHART_SENTIMENT_COLORS.very_positive);
    });
  });

  describe("value band colors (ENG-3331)", () => {
    const bandDim = "FeedbackRecords.valueBand";

    test("colors each band by polarity, NPS and CSAT alike", () => {
      expect(getSemanticDimensionColor(bandDim, "promoter")).toBe(CHART_VALUE_BAND_COLORS.positive);
      expect(getSemanticDimensionColor(bandDim, "satisfied")).toBe(CHART_VALUE_BAND_COLORS.positive);
      expect(getSemanticDimensionColor(bandDim, "passive")).toBe(CHART_VALUE_BAND_COLORS.neutral);
      expect(getSemanticDimensionColor(bandDim, "neutral")).toBe(CHART_VALUE_BAND_COLORS.neutral);
      expect(getSemanticDimensionColor(bandDim, "detractor")).toBe(CHART_VALUE_BAND_COLORS.negative);
      expect(getSemanticDimensionColor(bandDim, "dissatisfied")).toBe(CHART_VALUE_BAND_COLORS.negative);
      expect(getSemanticDimensionColor(bandDim, "very_positive")).toBeUndefined();
      expect(getSemanticDimensionColor(bandDim, null)).toBeUndefined();
    });

    test("gives the bucket count measures the color of their band", () => {
      expect(getBandMeasureColor("FeedbackRecords.promoterCount")).toBe(CHART_VALUE_BAND_COLORS.positive);
      expect(getBandMeasureColor("FeedbackRecords.passiveCount")).toBe(CHART_VALUE_BAND_COLORS.neutral);
      expect(getBandMeasureColor("FeedbackRecords.csatDissatisfiedCount")).toBe(
        CHART_VALUE_BAND_COLORS.negative
      );
      expect(getBandMeasureColor("FeedbackRecords.npsCount")).toBeUndefined();
      expect(getSemanticMeasureColor("FeedbackRecords.positiveCount")).toBe(CHART_SENTIMENT_COLORS.positive);
      expect(getSemanticMeasureColor("FeedbackRecords.detractorCount")).toBe(
        CHART_VALUE_BAND_COLORS.negative
      );
    });

    test("band slices keep their colors and leave the palette to the other slices", () => {
      const rows = [
        { [bandDim]: "promoter", count: 50 },
        { [bandDim]: "mystery", count: 40 },
        { [bandDim]: "detractor", count: 30 },
      ];
      expect(preparePieData(rows, "count", bandDim)?.colors).toEqual([
        CHART_VALUE_BAND_COLORS.positive,
        CHART_MEASURE_COLORS[0],
        CHART_VALUE_BAND_COLORS.negative,
      ]);
    });

    test("a pie of the three NPS bucket measures colors each slice by its band", () => {
      const slices = prepareMeasureSliceData(
        [
          {
            "FeedbackRecords.promoterCount": 184,
            "FeedbackRecords.passiveCount": 98,
            "FeedbackRecords.detractorCount": 64,
            "FeedbackRecords.count": 10,
          },
        ],
        [
          "FeedbackRecords.promoterCount",
          "FeedbackRecords.passiveCount",
          "FeedbackRecords.detractorCount",
          "FeedbackRecords.count",
        ],
        (key) => key
      );
      expect(preparePieData(slices, PIE_MEASURE_VALUE_KEY, PIE_MEASURE_NAME_KEY)?.colors).toEqual([
        CHART_VALUE_BAND_COLORS.positive,
        CHART_VALUE_BAND_COLORS.neutral,
        CHART_VALUE_BAND_COLORS.negative,
        CHART_MEASURE_COLORS[0],
      ]);
    });

    test("band count measures do not consume a palette slot when pivoted to categories", () => {
      const rows = pivotMeasuresToCategories(
        [{ "FeedbackRecords.promoterCount": 3, "FeedbackRecords.count": 9 }],
        ["FeedbackRecords.promoterCount", "FeedbackRecords.count"],
        (key) => key
      );
      expect(rows.map((row) => row.fill)).toEqual([
        CHART_VALUE_BAND_COLORS.positive,
        CHART_MEASURE_COLORS[0],
      ]);
    });
  });

  describe("getSentimentMeasureColor", () => {
    test("maps every sentiment count measure to the matching bucket color", () => {
      expect(getSentimentMeasureColor("FeedbackRecords.veryNegativeCount")).toBe(
        CHART_SENTIMENT_COLORS.very_negative
      );
      expect(getSentimentMeasureColor("FeedbackRecords.negativeCount")).toBe(CHART_SENTIMENT_COLORS.negative);
      expect(getSentimentMeasureColor("FeedbackRecords.neutralCount")).toBe(CHART_SENTIMENT_COLORS.neutral);
      expect(getSentimentMeasureColor("FeedbackRecords.positiveCount")).toBe(CHART_SENTIMENT_COLORS.positive);
      expect(getSentimentMeasureColor("FeedbackRecords.veryPositiveCount")).toBe(
        CHART_SENTIMENT_COLORS.very_positive
      );
      expect(getSentimentMeasureColor("FeedbackRecords.mixedCount")).toBe(CHART_SENTIMENT_COLORS.mixed);
    });

    test("returns undefined for non-sentiment measures", () => {
      expect(getSentimentMeasureColor("FeedbackRecords.count")).toBeUndefined();
      expect(getSentimentMeasureColor("FeedbackRecords.joyCount")).toBeUndefined();
      expect(getSentimentMeasureColor("FeedbackRecords.sentimentAverage")).toBeUndefined();
    });
  });

  describe("pivotMeasuresToCategories", () => {
    const label = (key: string) => `label:${key}`;

    test("pivots a single measure row into one category row per measure", () => {
      const data = [{ "F.veryPositiveCount": 3, "F.negativeCount": "1" }];
      const result = pivotMeasuresToCategories(data, ["F.veryPositiveCount", "F.negativeCount"], label);
      expect(result).toEqual([
        {
          [PIVOTED_MEASURE_KEY]: "F.veryPositiveCount",
          [PIVOTED_VALUE_KEY]: 3,
          tooltipLabel: "label:F.veryPositiveCount",
          fill: CHART_MEASURE_COLORS[0],
        },
        {
          [PIVOTED_MEASURE_KEY]: "F.negativeCount",
          [PIVOTED_VALUE_KEY]: 1,
          tooltipLabel: "label:F.negativeCount",
          fill: CHART_MEASURE_COLORS[1],
        },
      ]);
    });

    test("carries the response base column onto every pivoted row for the tooltip", () => {
      const data = [{ "F.promoterCount": 37, "F.detractorCount": 2, "F.npsCount": 48 }];
      const result = pivotMeasuresToCategories(
        data,
        ["F.promoterCount", "F.detractorCount"],
        label,
        "F.npsCount"
      );
      expect(result.map((row) => row["F.npsCount"])).toEqual([48, 48]);
      // Without a key nothing extra is carried, so existing pivoted rows keep their shape.
      expect(pivotMeasuresToCategories(data, ["F.promoterCount"], label)[0]).not.toHaveProperty("F.npsCount");
    });

    test("keeps the given measure order so bars fill the axis from the left", () => {
      const data = [{ b: 2, a: 1 }];
      const result = pivotMeasuresToCategories(data, ["a", "b"], label);
      expect(result.map((row) => row[PIVOTED_MEASURE_KEY])).toEqual(["a", "b"]);
    });

    test("keeps missing, null, and non-numeric values null so they never read as a measured zero", () => {
      const data = [{ a: null, b: "n/a" }];
      const result = pivotMeasuresToCategories(data, ["a", "b", "missing"], label);
      // A measure Cube computed as NULL (never asked) must not render the same as a real 0.
      expect(result.map((row) => row[PIVOTED_VALUE_KEY])).toEqual([null, null, null]);
    });

    test("distinguishes a genuine zero from a null measure", () => {
      const data = [{ scored: 0, notAsked: null }];
      const result = pivotMeasuresToCategories(data, ["scored", "notAsked"], label);
      expect(result.map((row) => row[PIVOTED_VALUE_KEY])).toEqual([0, null]);
    });

    test("emits one row per measure key when data is empty, with no value", () => {
      const result = pivotMeasuresToCategories([], ["a"], label);
      expect(result).toHaveLength(1);
      expect(result[0][PIVOTED_VALUE_KEY]).toBeNull();
    });

    test("cycles the palette when there are more measures than colors", () => {
      const keys = Array.from({ length: CHART_MEASURE_COLORS.length + 1 }, (_, i) => `m${i}`);
      const result = pivotMeasuresToCategories([{}], keys, label);
      expect(result.at(-1)?.fill).toBe(CHART_MEASURE_COLORS[0]);
    });

    test("sentiment count measures keep their semantic colors and don't consume palette hues", () => {
      const result = pivotMeasuresToCategories(
        [{}],
        ["FeedbackRecords.veryPositiveCount", "FeedbackRecords.count", "FeedbackRecords.mixedCount"],
        label
      );
      expect(result.map((row) => row.fill)).toEqual([
        CHART_SENTIMENT_COLORS.very_positive,
        CHART_MEASURE_COLORS[0],
        CHART_SENTIMENT_COLORS.mixed,
      ]);
    });
  });

  describe("constants", () => {
    test("CHART_MEASURE_COLORS has no duplicate hues", () => {
      expect(new Set(CHART_MEASURE_COLORS).size).toBe(CHART_MEASURE_COLORS.length);
    });

    test("CHART_SENTIMENT_COLORS covers every enum value with distinct colors", () => {
      expect(Object.keys(CHART_SENTIMENT_COLORS).sort()).toEqual([...HUB_SENTIMENT_VALUES].sort());
      const colors = Object.values(CHART_SENTIMENT_COLORS);
      expect(new Set(colors).size).toBe(colors.length);
      // the semantic scale must not collide with the "not enriched" gray
      expect(colors).not.toContain(CHART_NOT_ENRICHED_COLOR);
    });
  });
});

describe("flipped bar axis sizing", () => {
  test("sizes the category gutter to the labels present", () => {
    // Three numeric categories used to leave ~150px of empty gutter before the bars started.
    expect(getCategoryAxisWidth(["3", "10", "25"])).toBeLessThan(CATEGORY_AXIS_MIN_CEILING / 2);
  });

  test("never drops below the floor or above the ceiling", () => {
    expect(getCategoryAxisWidth(["1"])).toBe(CATEGORY_AXIS_MIN_WIDTH);
    expect(getCategoryAxisWidth([])).toBe(CATEGORY_AXIS_MIN_WIDTH);
    expect(getCategoryAxisWidth(["How satisfied are you with the checkout experience overall?"])).toBe(
      CATEGORY_AXIS_MIN_CEILING
    );
  });

  test("takes the longest label, not the first or last", () => {
    const width = getCategoryAxisWidth(["ok", "a considerably longer label", "no"]);
    expect(width).toBe(getCategoryAxisWidth(["a considerably longer label"]));
  });

  // ENG-3223: the flat 160px cap meant widening a chart from a dashboard widget to the editor gave
  // every new pixel to the bars while the labels stayed cut at the same point.
  describe("gutter scales with the chart", () => {
    // Two real questions from the KAS pre-match survey; the longest is 45 characters.
    const LONG_LABELS = [
      "CSAT With clarity of screening procedures",
      "CSAT with AHLAN pre-match accommodation",
    ];
    const WIDGET_WIDTH = 502;
    const EDITOR_WIDTH = 924;

    test("a wider chart gets a wider gutter, up to what the longest label needs", () => {
      const needed = getCategoryAxisWidth(LONG_LABELS, 100_000);
      const inWidget = getCategoryAxisWidth(LONG_LABELS, WIDGET_WIDTH);
      const inEditor = getCategoryAxisWidth(LONG_LABELS, EDITOR_WIDTH);

      // The widget cannot fit the label, so the gutter takes its full share of the width.
      expect(inWidget).toBe(Math.floor(WIDGET_WIDTH * CATEGORY_AXIS_MAX_SHARE));
      expect(inWidget).toBeLessThan(needed);
      // The editor can, so the gutter stops at the label rather than at the share.
      expect(inEditor).toBe(needed);
      expect(inEditor).toBeLessThan(Math.floor(EDITOR_WIDTH * CATEGORY_AXIS_MAX_SHARE));
      expect(inEditor).toBeGreaterThan(inWidget);
    });

    test("leaves the plot the clear majority of the chart at any width from a widget up", () => {
      for (const chartWidth of [480, WIDGET_WIDTH, EDITOR_WIDTH, 1600]) {
        const gutter = getCategoryAxisWidth(LONG_LABELS, chartWidth);
        expect(chartWidth - gutter).toBeGreaterThanOrEqual(gutter * 2);
      }
    });

    test("a widget too narrow for a third to be worth anything keeps the gutter it had", () => {
      // A quarter-width dashboard widget; a third of it is under the flat ceiling.
      expect(getCategoryAxisWidth(LONG_LABELS, 377)).toBe(CATEGORY_AXIS_MIN_CEILING);
    });

    test("never claims more than the longest label needs, however wide the chart", () => {
      const unbounded = getCategoryAxisWidth(["Gender", "Nationality"]);
      expect(getCategoryAxisWidth(["Gender", "Nationality"], 4000)).toBe(unbounded);
      expect(unbounded).toBeLessThan(CATEGORY_AXIS_MIN_CEILING);
    });

    test("keeps the flat ceiling until the chart has been measured", () => {
      for (const unmeasured of [undefined, 0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {
        expect(getCategoryAxisWidth(LONG_LABELS, unmeasured)).toBe(CATEGORY_AXIS_MIN_CEILING);
      }
    });

    test("short labels keep the floor on any chart", () => {
      expect(getCategoryAxisWidth(["1"], 60)).toBe(CATEGORY_AXIS_MIN_WIDTH);
      expect(getCategoryAxisWidth(["1"], 4000)).toBe(CATEGORY_AXIS_MIN_WIDTH);
    });
  });

  test("reserves room for the widest value label so the longest bar keeps its number", () => {
    // The bug this guards: with no padding the label of a bar reaching the axis bound is anchored
    // at the plot edge and clipped by the SVG viewport.
    expect(getValueLabelPadding(["50", "20", "5"])).toBeGreaterThanOrEqual(VALUE_LABEL_MIN_PADDING);
    expect(getValueLabelPadding(["1,234,567"])).toBeGreaterThan(getValueLabelPadding(["5"]));
  });

  test("caps the value gutter so a huge number cannot eat the plot", () => {
    expect(getValueLabelPadding(["123,456,789,012,345"])).toBe(VALUE_LABEL_MAX_PADDING);
  });
});

describe("category label truncation", () => {
  // The gutter caps at CATEGORY_AXIS_MIN_CEILING and the tick hands the helper `axisWidth - gap`.
  const BOX_WIDTH = 152;
  // Two real questions from the KAS pre-match survey, which share nineteen leading characters.
  const CLARITY_SCREENING = "CSAT With clarity of screening procedures";
  const CLARITY_INFO = "CSAT with clarity of information";

  test("leaves a label that already fits alone", () => {
    expect(truncateLabelToBox("Gender", BOX_WIDTH, 1)).toBe("Gender");
  });

  // ENG-3148: tail truncation printed the shared opening words against every bar, so a dense axis
  // read "CSAT with clarity of…" all the way down and the rows could not be told apart.
  test("keeps the distinguishing tail when labels share an opening", () => {
    const screening = truncateLabelToBox(CLARITY_SCREENING, BOX_WIDTH, 1);
    const info = truncateLabelToBox(CLARITY_INFO, BOX_WIDTH, 1);

    expect(screening).not.toBe(info);
    expect(screening.endsWith("procedures")).toBe(true);
    expect(screening).toContain("…");
  });

  test("spends the whole box: more lines cut less", () => {
    const oneLine = truncateLabelToBox(CLARITY_SCREENING, BOX_WIDTH, 1);
    const threeLines = truncateLabelToBox(CLARITY_SCREENING, BOX_WIDTH, 3);

    expect(threeLines.length).toBeGreaterThan(oneLine.length);
    expect(threeLines).toBe(CLARITY_SCREENING);
  });

  test("cuts to what the box can show, so the CSS clamp is not what the reader meets", () => {
    const capacity = Math.floor(BOX_WIDTH / 6.5);

    expect(truncateLabelToBox(CLARITY_SCREENING, BOX_WIDTH, 1).length).toBeLessThanOrEqual(capacity);
  });

  test("says something rather than nothing in a box with no room", () => {
    expect(truncateLabelToBox("Nationality", 10, 1)).toBe("…");
    expect(truncateLabelToBox("Nationality", 20, 1)).toContain("…");
  });

  // recharts has not measured the axis on the first render, and a guessed cut there would stick.
  test("returns the label untouched when the box is not measured yet", () => {
    expect(truncateLabelToBox(CLARITY_SCREENING, Number.NaN, 1)).toBe(CLARITY_SCREENING);
    expect(truncateLabelToBox(CLARITY_SCREENING, 0, 1)).toBe(CLARITY_SCREENING);
    expect(truncateLabelToBox(CLARITY_SCREENING, BOX_WIDTH, 0)).toBe(CLARITY_SCREENING);
  });
});

describe("wrapped category label box", () => {
  // ENG-3148: the budget used to come from the band (plotHeight / rowCount), so the same question
  // wrapped over three lines on a sparse CES chart and clamped to one on a dense CSAT chart of the
  // same questions at the same width. Row count is out of the treatment now.
  test("gives every chart one line, whatever its row count leaves per band", () => {
    for (const band of [12, 24, 40, 56, 200, 1000]) {
      expect(getCategoryLabelLineClamp()).toBe(CATEGORY_AXIS_LABEL_LINES);
      expect(getCategoryLabelBoxHeight(band)).toBeLessThanOrEqual(AXIS_LABEL_LINE_HEIGHT);
    }
  });

  test("never overlaps the neighbouring label, however tight the band", () => {
    for (const band of [12, 24, 40, 56, 200]) {
      expect(getCategoryLabelBoxHeight(band)).toBeLessThanOrEqual(band - AXIS_LABEL_GAP);
    }
  });

  test("keeps a box worth showing when the band cannot hold a line at all", () => {
    expect(getCategoryLabelBoxHeight(4)).toBeGreaterThan(0);
  });

  test("assumes the full line before recharts has measured the axis", () => {
    expect(getCategoryLabelBoxHeight(undefined)).toBe(AXIS_LABEL_LINE_HEIGHT);
    expect(getCategoryLabelBoxHeight(Number.NaN)).toBe(AXIS_LABEL_LINE_HEIGHT);
  });
});

describe("formatPercentShare", () => {
  test("keeps one fraction digit, so a small real share is not rounded away to 0%", () => {
    // 2 records out of 500: the section is drawn and hoverable, so its label must not read "0%".
    expect(formatPercentShare(0.004, "en-US")).toBe("0.4%");
    expect(formatPercentShare(1 / 3, "en-US")).toBe("33.3%");
    expect(formatPercentShare(1, "en-US")).toBe("100.0%");
  });

  test("follows the locale's decimal separator instead of a hardcoded period", () => {
    const de = formatPercentShare(0.125, "de-DE");
    expect(de).toContain("12,5");
    expect(de).not.toContain("12.5");
  });
});

describe("crowded category axis", () => {
  test("wraps while each label keeps its minimum box, rotates below it", () => {
    expect(shouldRotateCategoryLabels(5, 800)).toBe(false);
    expect(shouldRotateCategoryLabels(25, 800)).toBe(true);
    expect(shouldRotateCategoryLabels(25, undefined)).toBe(false);
    expect(shouldRotateCategoryLabels(1, 50)).toBe(false);
  });

  test("rotated labels are cut from the middle and reserve their diagonal", () => {
    const long = "How satisfied are you with the onboarding checklist?";
    const cut = truncateRotatedLabel(long);
    expect(cut.length).toBeLessThanOrEqual(24);
    expect(cut).toContain("…");
    expect(cut.endsWith("checklist?")).toBe(true);
    expect(truncateRotatedLabel("Short")).toBe("Short");
    expect(getRotatedAxisHeight(["Short"])).toBeLessThan(getRotatedAxisHeight([long]));
  });
});

describe("getLegendHeight", () => {
  test("one row for a few entries, more rows as entries wrap", () => {
    expect(getLegendHeight(["A", "B"], 800)).toBe(36);
    const many = Array.from({ length: 30 }, (_, i) => `Source number ${i}`);
    expect(getLegendHeight(many, 800)).toBeGreaterThan(36);
  });

  test("never reserves more than its share of the chart height", () => {
    const many = Array.from({ length: 40 }, (_, i) => `Source number ${i}`);
    expect(getLegendHeight(many, 400, 300)).toBe(90);
    expect(getLegendHeight(["A"], 400, 300)).toBe(36);
  });
});
