import { format, isValid, parseISO } from "date-fns";
import { EMPTY_GROUP_VALUE } from "@/modules/ee/analysis/charts/lib/chart-series";
import {
  EMOTIONS_DIMENSION_ID,
  SENTIMENT_DIMENSION_ID,
  type TEmotionValue,
  type TSentimentValue,
  type TValueBandPolarity,
  VALUE_BAND_DIMENSION_ID,
  VALUE_BAND_POLARITY,
  getEmotionValueForMeasureId,
  getSentimentValueForMeasureId,
  isEmotionValue,
  isNotEnrichedDimensionValue,
  isSentimentValue,
  isValueBandValue,
} from "@/modules/ee/analysis/lib/schema-definition";
import type { TChartDataRow, TChartType } from "@/modules/ee/analysis/types/analysis";
import { ZChartType } from "@/modules/ee/analysis/types/analysis";

export const CHART_BRAND_DARK = "#00C4B8";
export const CHART_BRAND_LIGHT = "#00E6CA";

/**
 * Shared categorical palette for bar cells, pie slices, and multi-measure series. Assigned by index
 * (never cycled for meaning). Eight distinct hues, ordered to maximize adjacent colorblind
 * separation — validated with the dataviz palette script (worst adjacent CVD ΔE ≈ 38 on white, well
 * above the ≥12 target). The previous 6-hue set repeated teal (#00C4B8 vs #14b8a6) and blue/violet,
 * which collided on the 6-category emotion/sentiment charts.
 */
export const CHART_MEASURE_COLORS = [
  CHART_BRAND_DARK, // teal (brand)
  "#2a78d6", // blue
  "#eda100", // yellow
  "#e34948", // red
  "#4a3aa7", // violet
  "#eb6834", // orange
  "#e87ba4", // magenta
  "#008300", // green
];

/** Neutral gray for the "not enriched" bucket (empty sentiment/emotion values). A true gray (no
 * slate blue cast) that reads as muted in both light and dark so it doesn't compete with the
 * categorical palette. */
export const CHART_NOT_ENRICHED_COLOR = "#a3a3a3"; // neutral-400

/** Red → green steps shared by every scale that runs from bad to good (sentiment, NPS and CSAT
 * bands), so "bad" and "good" read the same on every chart of a dashboard. */
const CHART_SCALE_RED = "#e34948";
const CHART_SCALE_ORANGE = "#eb6834";
const CHART_SCALE_AMBER = "#eda100";
const CHART_SCALE_LIGHT_GREEN = "#62b33f";
const CHART_SCALE_GREEN = "#008300";

/**
 * Semantic scale for sentiment buckets, keyed by enum value (never by series index) so each bucket
 * keeps its color regardless of which buckets appear: red for very negative through amber for
 * neutral to green for very positive. "Mixed" sits off the scale, so it takes violet — not a step
 * of the red → green run a reader would place it on.
 */
export const CHART_SENTIMENT_COLORS: Record<TSentimentValue, string> = {
  very_negative: CHART_SCALE_RED,
  negative: CHART_SCALE_ORANGE,
  neutral: CHART_SCALE_AMBER,
  positive: CHART_SCALE_LIGHT_GREEN,
  very_positive: CHART_SCALE_GREEN,
  mixed: "#4a3aa7", // violet
};

/**
 * Polarity colors for NPS and CSAT bands: promoter/satisfied green, passive/neutral amber,
 * detractor/dissatisfied red — the traffic light NPS readers expect, on the same steps as the
 * sentiment scale.
 */
export const CHART_VALUE_BAND_COLORS: Record<TValueBandPolarity, string> = {
  positive: CHART_SCALE_GREEN,
  neutral: CHART_SCALE_AMBER,
  negative: CHART_SCALE_RED,
};

/**
 * One fixed color per emotion, so an emotion keeps its color whichever emotions a chart picks and in
 * whatever order (the palette-by-index it replaced painted "joy" teal on one chart and blue on the
 * next). Hues follow the common emotion color associations — joy yellow, sadness blue, anger red,
 * fear violet, disgust green, surprise orange — all from the validated categorical palette.
 */
export const CHART_EMOTION_COLORS: Record<TEmotionValue, string> = {
  joy: "#eda100",
  surprise: "#eb6834",
  anger: "#e34948",
  sadness: "#2a78d6",
  fear: "#4a3aa7",
  disgust: "#008300",
};

/**
 * Semantic color for an enum dimension value: gray for the "not enriched" bucket, the sentiment
 * scale for sentiment values, polarity colors for value bands. Returns undefined when the value has no semantic color (other
 * dimensions, unknown tokens) so callers fall back to the generic palette.
 */
export const getSemanticDimensionColor = (dimensionId: string, value: unknown): string | undefined => {
  // The shown empty group ("(no value)", "Not enriched", "Unspecified") is gray on every chart type.
  if (value === EMPTY_GROUP_VALUE || isNotEnrichedDimensionValue(dimensionId, value)) {
    return CHART_NOT_ENRICHED_COLOR;
  }
  if (dimensionId === SENTIMENT_DIMENSION_ID && typeof value === "string" && isSentimentValue(value)) {
    return CHART_SENTIMENT_COLORS[value];
  }
  if (dimensionId === VALUE_BAND_DIMENSION_ID && typeof value === "string" && isValueBandValue(value)) {
    return CHART_VALUE_BAND_COLORS[VALUE_BAND_POLARITY[value]];
  }
  // Only a record tagged with one emotion has an emotion's color; a combination ("joy, fear") is a
  // group of its own and takes the palette.
  if (dimensionId === EMOTIONS_DIMENSION_ID && typeof value === "string" && isEmotionValue(value)) {
    return CHART_EMOTION_COLORS[value];
  }
  return undefined;
};

/** Semantic series color for the sentiment count measures (e.g. "FeedbackRecords.veryPositiveCount"),
 * matching the dimension buckets. Undefined for every other measure. */
export const getSentimentMeasureColor = (measureId: string): string | undefined => {
  const value = getSentimentValueForMeasureId(measureId);
  return value ? CHART_SENTIMENT_COLORS[value] : undefined;
};

const BAND_MEASURE_POLARITY = new Map<string, TValueBandPolarity>([
  ["FeedbackRecords.promoterCount", "positive"],
  ["FeedbackRecords.passiveCount", "neutral"],
  ["FeedbackRecords.detractorCount", "negative"],
  ["FeedbackRecords.csatSatisfiedCount", "positive"],
  ["FeedbackRecords.csatNeutralCount", "neutral"],
  ["FeedbackRecords.csatDissatisfiedCount", "negative"],
]);

/** Band polarity color for the NPS/CSAT bucket count measures, matching the valueBand dimension. */
export const getBandMeasureColor = (measureId: string): string | undefined => {
  const polarity = BAND_MEASURE_POLARITY.get(measureId);
  return polarity ? CHART_VALUE_BAND_COLORS[polarity] : undefined;
};

/** Fixed color for an emotion count measure (e.g. "FeedbackRecords.joyCount"). */
export const getEmotionMeasureColor = (measureId: string): string | undefined => {
  const emotion = getEmotionValueForMeasureId(measureId);
  return emotion ? CHART_EMOTION_COLORS[emotion] : undefined;
};

/** Meaning-bound series color for a measure (sentiment, emotion or band counts), or undefined for the palette. */
export const getSemanticMeasureColor = (measureId: string): string | undefined =>
  getSentimentMeasureColor(measureId) ?? getEmotionMeasureColor(measureId) ?? getBandMeasureColor(measureId);

/**
 * Chart types that no longer exist, mapped to the type that replaced them. `line` merged into
 * `area` as the `areaDisplay: "line"` style, so anything still holding the old value — an AI
 * response, a cached payload — lands on the merged type instead of the "bar" fallback. The
 * display style is not recovered here; the migration is what carries it for stored charts.
 */
const LEGACY_CHART_TYPE_ALIASES = new Map<string, TChartType>([["line", "area"]]);

/** Validate a chart type string, mapping retired types forward and defaulting to "bar". */
export const resolveChartType = (raw: string): TChartType => {
  const parsed = ZChartType.safeParse(raw);
  if (parsed.success) return parsed.data;
  return LEGACY_CHART_TYPE_ALIASES.get(raw) ?? "bar";
};

const isNumericValue = (val: unknown): boolean => {
  if (val === null || val === undefined || val === "") return false;
  const num = Number(val);
  return !Number.isNaN(num) && Number.isFinite(num);
};

export const PIE_MEASURE_NAME_KEY = "__measureName";
export const PIE_MEASURE_VALUE_KEY = "__measureValue";
/** The measure a slice came from, so the slice can take the measure's semantic color. */
export const PIE_MEASURE_ID_KEY = "__measureId";

/** A slice's meaning-bound color: its measure's (measure slices) or its dimension value's. */
const getSliceSemanticColor = (row: TChartDataRow, nameKey?: string): string | undefined => {
  const measureId = row[PIE_MEASURE_ID_KEY];
  if (typeof measureId === "string") return getSemanticMeasureColor(measureId);
  return nameKey ? getSemanticDimensionColor(nameKey, row[nameKey]) : undefined;
};

export const preparePieData = (
  data: TChartDataRow[],
  dataKey: string,
  nameKey?: string
): { processedData: TChartDataRow[]; colors: string[] } | null => {
  // Drop zero-value rows alongside non-numeric ones. With `minAngle={2}` on
  // `<Pie>`, a `value: 0` slice gets stretched to 2° of visible arc and the
  // label math (driven by midAngle) then implies a non-zero share, so callouts
  // line up off the data. Trade-off: real "0" categories (e.g. a Neutral
  // sentiment bucket with no responses) disappear from both the pie and the
  // legend; surfacing those in the legend is tracked as a follow-up.
  const validData = data.filter((row) => isNumericValue(row[dataKey]) && Number(row[dataKey]) > 0);
  const processedData = validData
    .map((row) => ({ ...row, [dataKey]: Number(row[dataKey]) }))
    .sort((a, b) => Number(b[dataKey]) - Number(a[dataKey]));
  if (processedData.length === 0) return null;

  // Semantic slices (the gray "not enriched" bucket, the sentiment scale) keep their meaning-bound
  // colors; palette colors are handed out only to the remaining slices so a semantic bucket doesn't
  // consume a categorical hue.
  let paletteIndex = 0;
  const colors = processedData.map((row) => {
    const semanticColor = getSliceSemanticColor(row, nameKey);
    if (semanticColor) return semanticColor;
    const color = CHART_MEASURE_COLORS[paletteIndex % CHART_MEASURE_COLORS.length];
    paletteIndex++;
    return color;
  });
  return { processedData, colors };
};

/**
 * Pivot several measures (one/few rows, N measure columns) into one row per measure, so a pie
 * chart with multiple measures and no dimension renders a slice per measure instead of only the
 * first one. Each measure is summed across the given rows.
 *
 * The measure label is stored a second time as `tooltipLabel` because the tooltip keys its row
 * label off the dataKey, which here is the internal PIE_MEASURE_VALUE_KEY rather than a Cube
 * column — without it the tooltip prettifies that key and shows "__measure Value" (ENG-2346).
 */
export const prepareMeasureSliceData = (
  rows: TChartDataRow[],
  measureKeys: string[],
  labelFor: (key: string) => string,
  /** Column to carry onto every slice, summed like the measures, so the tooltip can print "n = …". */
  responseBaseKey?: string
): TChartDataRow[] => {
  const sumColumn = (key: string): number =>
    rows.reduce((sum, row) => sum + (isNumericValue(row[key]) ? Number(row[key]) : 0), 0);
  const responseBase = responseBaseKey ? { [responseBaseKey]: sumColumn(responseBaseKey) } : {};
  return measureKeys.map((key) => ({
    [PIE_MEASURE_NAME_KEY]: labelFor(key),
    [PIE_MEASURE_ID_KEY]: key,
    [PIE_MEASURE_VALUE_KEY]: sumColumn(key),
    tooltipLabel: labelFor(key),
    ...responseBase,
  }));
};

/**
 * Format a 0-1 share as a percentage for display, in the app's active language. One fraction digit
 * throughout: whole percents print a real 0.4% group as "0%" and make three equal groups add up to
 * 99%, and the pie's slice labels and the breakdown bar's legend must agree to the digit, since
 * they are two displays of one chart.
 *
 * `Intl` rather than `toFixed` so the decimal separator and the percent sign follow the locale
 * ("12,5 %" in de-DE), which a hardcoded "%" suffix cannot do.
 */
export const formatPercentShare = (percent: number, locale?: string): string =>
  new Intl.NumberFormat(locale, {
    style: "percent",
    minimumFractionDigits: 1,
    maximumFractionDigits: 1,
  }).format(percent);

/** One section of the single-bar distribution chart (a pie chart's "Breakdown bars" display). */
export interface TDistributionSegment {
  /** Stable react key: the dimension value or the measure id the segment came from. */
  key: string;
  label: string;
  value: number;
  /** Share of the total, 0-1. */
  percent: number;
  color: string;
}

/** Input to {@link buildDistributionSegments}: one candidate section, color optional. */
export interface TDistributionEntry {
  key: string;
  label: string;
  value: unknown;
  /** Meaning-bound color (sentiment scale, "not enriched" gray); palette color when absent. */
  color?: string;
}

/**
 * Turn labelled values into the sections of a single 100% bar: coerce to numbers, compute each
 * section's share, and hand out palette colors to the entries that carry no semantic color (so a
 * semantic bucket never consumes a categorical hue, as in preparePieData).
 *
 * Zero and negative entries are dropped: they would render as a zero-width, unhoverable section.
 * Sections are ordered largest share first, the order and therefore the palette handout
 * preparePieData uses, so switching a pie between its two displays doesn't move or recolour a
 * group. Sorting is stable, so equal shares keep the caller's order. Returns null when nothing is
 * left to show, i.e. the total is not positive.
 */
export function buildDistributionSegments(
  entries: readonly TDistributionEntry[]
): { segments: TDistributionSegment[]; total: number } | null {
  let paletteIndex = 0;
  const scaled = entries
    .map((entry) => ({
      key: entry.key,
      label: entry.label,
      value: isNumericValue(entry.value) ? Number(entry.value) : 0,
      color: entry.color,
    }))
    .filter((entry) => entry.value > 0)
    .sort((a, b) => b.value - a.value);

  const total = scaled.reduce((sum, entry) => sum + entry.value, 0);
  if (total <= 0) return null;

  const segments = scaled.map(({ key, label, value, color }) => {
    let resolvedColor = color;
    if (!resolvedColor) {
      resolvedColor = CHART_MEASURE_COLORS[paletteIndex % CHART_MEASURE_COLORS.length];
      paletteIndex++;
    }
    return { key, label, value, percent: value / total, color: resolvedColor };
  });

  return { segments, total };
}

/** Category key for rows produced by {@link pivotMeasuresToCategories}. */
export const PIVOTED_MEASURE_KEY = "measure";
/** Value key for rows produced by {@link pivotMeasuresToCategories}. */
export const PIVOTED_VALUE_KEY = "value";

/**
 * Pivot a measure-only result row (one row with one column per measure) into one category row
 * per measure. Rendering the raw row as N bar series leaves recharts with a single category
 * band centered in the plot — a wide empty gap before the first bar. Pivoted, the measures
 * become ordinary categories that fill the x-axis from the left.
 *
 * Missing/non-numeric values stay null: the measure keeps its slot on the axis, but renders as a
 * gap rather than as a zero-height bar labelled 0.
 * `formatLabel` supplies the translated measure label stored as `tooltipLabel` on each row.
 */
export function pivotMeasuresToCategories(
  data: TChartDataRow[],
  measureKeys: string[],
  formatLabel: (measureKey: string) => string,
  /** Column to carry onto every pivoted row, so the tooltip can still print "n = …" for each bar. */
  responseBaseKey?: string
): TChartDataRow[] {
  const row = data[0] ?? {};
  // Like preparePieData: semantic buckets (sentiment counts) keep their meaning-bound colors and
  // don't consume a categorical hue; the palette is handed out only to the remaining measures.
  let paletteIndex = 0;
  return measureKeys.map((key) => {
    const num = Number(row[key]);
    let fill = getSemanticMeasureColor(key);
    if (!fill) {
      fill = CHART_MEASURE_COLORS[paletteIndex % CHART_MEASURE_COLORS.length];
      paletteIndex++;
    }
    return {
      // A measure that computed to NULL stays null: recharts leaves a gap and the value label
      // renders empty, so "not asked" no longer looks like a measured zero.
      [PIVOTED_VALUE_KEY]: isNumericValue(row[key]) && Number.isFinite(num) ? num : null,
      [PIVOTED_MEASURE_KEY]: key,
      tooltipLabel: formatLabel(key),
      fill,
      ...(responseBaseKey ? { [responseBaseKey]: row[responseBaseKey] } : {}),
    };
  });
}

// parseISO accepts year-only inputs (e.g. "1000" → Jan 1, 1000); require a
// full YYYY-MM-DD prefix so numeric category labels aren't formatted as dates.
const ISO_DATE_PREFIX = /^\d{4}-\d{2}-\d{2}/;

const isLikelyIsoDateString = (str: string): boolean => ISO_DATE_PREFIX.test(str);

/** Format a value for x-axis ticks; ISO date strings become "MMM d, yyyy", others pass through. */
export function formatXAxisTick(value: unknown): string {
  if (value == null) return "";
  let str: string;
  if (typeof value === "string") str = value;
  else if (typeof value === "number") str = String(value);
  else return "";
  if (!isLikelyIsoDateString(str)) return str;
  const date = parseISO(str);
  if (isValid(date)) return format(date, "MMM d, yyyy");
  return str;
}

/**
 * Format a cell value for display in tables and tooltips.
 * ISO date strings become "MMM d, yyyy"; numbers stay as-is (formatted); objects are stringified.
 */
export function formatCellValue(value: unknown): string {
  if (value == null) return "";
  if (typeof value === "number") return value.toLocaleString(undefined, { maximumFractionDigits: 2 });
  if (typeof value === "string") {
    if (!isLikelyIsoDateString(value)) return value;
    const date = parseISO(value);
    if (isValid(date)) return format(date, "MMM d, yyyy");
    return value;
  }
  if (typeof value === "object") return JSON.stringify(value);
  if (typeof value === "boolean" || typeof value === "bigint") return String(value);
  return "";
}

// ── Flipped (horizontal) bar chart axis sizing ────────────────────────────────
// Both of these size a gutter to the text that will actually sit in it, rather than claiming a flat
// maximum: a flat gutter reads as a broken layout when the labels are short (three numeric
// categories left ~150px of empty space before the bars started).

/** Approximate advance width (px) of one character at `text-xs`, for sizing a gutter to the text
 * that will sit in it. Errs narrow on purpose: over-estimating the gutter steals plot width from
 * the bars, and the cap below is what a long label really lands on anyway. */
const AXIS_CHAR_WIDTH = 6.5;

/** The same advance width for deciding how much text *fits* a box, where the bias has to run the
 * other way: measured against the rendered ui-sans-serif at 12px, a mixed-case question label
 * averages ~6.6px per character, so sizing capacity with the gutter's estimate let a label that
 * only just overran its box escape truncation and paint outside it. */
const AXIS_CHAR_WIDTH_WIDE = 7;
/** Gap (px) between a tick's text and the axis line. Exported so the flipped tick positions its box
 * with the same clearance this module budgets for it, rather than borrowing {@link AXIS_LABEL_GAP},
 * which measures the space between two neighbouring labels. */
export const AXIS_TICK_GAP = 8;

/** Share of the chart's width the category gutter may claim at most, so the bars keep the clear
 * majority of the plot however long the labels run. Labels longer than that share are cut inside
 * the gutter (see `truncateLabelToBox`). */
export const CATEGORY_AXIS_MAX_SHARE = 1 / 3;
/** Least ceiling (px) for the category gutter: what the share above may never cut below, so a
 * narrow dashboard widget keeps the gutter it always had, and what the gutter caps at while the
 * chart's width is not known yet (the server render and the responsive container's first pass).
 * Wide enough for a short question label; longer labels are cut inside it. */
export const CATEGORY_AXIS_MIN_CEILING = 160;
/** Floor (px), so a one-character label still has a readable gutter. */
export const CATEGORY_AXIS_MIN_WIDTH = 28;

/**
 * Width (px) for the left-hand category gutter of a flipped bar chart: what the longest label
 * needs, capped at `CATEGORY_AXIS_MAX_SHARE` of the chart's width or `CATEGORY_AXIS_MIN_CEILING`,
 * whichever is more.
 *
 * The cap scales with the chart because the gutter is the half that needs the room: widening a chart
 * from a dashboard widget to the full-screen editor used to hand every new pixel to bars that were
 * already legible while the labels stayed cut at the same point (ENG-3223). It never claims more
 * than the longest label needs, so short labels keep a narrow gutter on any chart, and it never
 * drops below the flat ceiling it used to have, so narrow widgets read exactly as before.
 *
 * `chartWidth` has to be the width recharts is about to lay the chart out with — the tick boxes and
 * the plot offset are both derived from this number in the same render, so a width that arrives
 * later leaves the two disagreeing about where the gutter ends and the labels paint under the bars.
 * Unknown (`undefined`, non-finite or non-positive) means the flat ceiling alone.
 */
export const getCategoryAxisWidth = (labels: string[], chartWidth?: number): number => {
  const longest = labels.reduce((max, label) => Math.max(max, label.length), 0);
  const needed = Math.ceil(longest * AXIS_CHAR_WIDTH) + AXIS_TICK_GAP * 2;
  const measured = chartWidth !== undefined && Number.isFinite(chartWidth) && chartWidth > 0;
  const share = measured ? Math.floor(chartWidth * CATEGORY_AXIS_MAX_SHARE) : 0;
  const ceiling = Math.max(CATEGORY_AXIS_MIN_CEILING, share);
  return Math.min(ceiling, Math.max(CATEGORY_AXIS_MIN_WIDTH, needed));
};

// ── Wrapped axis label sizing ─────────────────────────────────────────────────
// Both axes render their category labels into a `foreignObject` so long question text can wrap.
// These describe that box, and are shared with the tick components so the space a chart reserves
// and the space a label is allowed to use are derived from the same numbers.

/** Line height (px) of a wrapped axis label at `text-xs`/`leading-tight`: ~15px for 12px text, plus
 * a hair of headroom so descenders on the last line are not clipped. */
export const AXIS_LABEL_LINE_HEIGHT = 16;
/** Lines a wrapped axis label may use before it clamps. */
export const AXIS_LABEL_MAX_LINES = 3;
/** Gap (px) kept between adjacent axis labels so wrapped text never touches its neighbour. */
export const AXIS_LABEL_GAP = 8;
/** Height (px) of a label box using the full line budget. */
export const AXIS_LABEL_BOX_HEIGHT = AXIS_LABEL_MAX_LINES * AXIS_LABEL_LINE_HEIGHT;

/** Height (px) a chart legend occupies — the `height` handed to `<ChartLegend>`. */
export const CHART_LEGEND_HEIGHT = 36;

/**
 * Lines a flipped category label uses: one, whatever the row count.
 *
 * This is the whole of ENG-3148. Deriving the budget from the band — `plotHeight / rowCount` —
 * meant the same question rendered differently depending on how many rows sat beside it: a CES
 * chart wrapped over three lines while a CSAT chart of the same questions at the same width used
 * one, so the two charts could not be read the same way. A fixed single line takes row count out of
 * the treatment entirely; what a label shows then depends only on the gutter and its own length,
 * and {@link truncateLabelToBox} makes one line carry the distinguishing words.
 *
 * The x-axis is unaffected — its labels sit side by side, where the constraint is width, not
 * density, and {@link AXIS_LABEL_MAX_LINES} still applies.
 */
export const CATEGORY_AXIS_LABEL_LINES = 1;

/**
 * Height (px) of the label box inside a category band of `band` px.
 *
 * One line's worth, less whatever a band too tight to hold even that leaves — bands that small
 * belong to a chart with more rows than its container can show, where the labels overlap whatever
 * we do. A missing or non-finite band means recharts has not measured the axis yet, which changes
 * nothing now that the budget no longer depends on it.
 */
export const getCategoryLabelBoxHeight = (band?: number): number => {
  const fullBudget = CATEGORY_AXIS_LABEL_LINES * AXIS_LABEL_LINE_HEIGHT;
  if (band === undefined || !Number.isFinite(band)) return fullBudget;
  return Math.max(1, Math.min(fullBudget, band - AXIS_LABEL_GAP));
};

/** Lines a flipped category label may use. Constant by design — see {@link CATEGORY_AXIS_LABEL_LINES}. */
export const getCategoryLabelLineClamp = (): number => CATEGORY_AXIS_LABEL_LINES;

/** Marks where the middle of a label was dropped. One character wide for the capacity arithmetic. */
const ELLIPSIS = "…";

/**
 * A category label cut to what its box can show, from the middle.
 *
 * Question labels in one survey share their opening words — "CSAT with clarity of screening
 * procedures", "CSAT with clarity of information" — so a tail-truncated axis prints the same
 * "CSAT with clarity of…" against every bar and the rows stop being tellable apart (ENG-3148). The
 * distinguishing words sit at the end, so the middle is what goes: "CSAT with clarity o…rocedures".
 *
 * Capacity is estimated from {@link AXIS_CHAR_WIDTH_WIDE}, which over-estimates each character so
 * a label that only just overruns its box is still cut. The CSS line clamp stays as the backstop
 * for anything wider still; this keeps that clamp from being what the reader normally meets.
 */
export const truncateLabelToBox = (label: string, boxWidth: number, lines: number): string => {
  if (!Number.isFinite(boxWidth) || !Number.isFinite(lines) || boxWidth <= 0 || lines <= 0) return label;

  const capacity = Math.max(1, Math.floor(boxWidth / AXIS_CHAR_WIDTH_WIDE)) * Math.floor(lines);
  if (label.length <= capacity) return label;
  // Too little room to say anything from both ends: one end plus the mark reads better than two
  // single characters around it.
  if (capacity <= ELLIPSIS.length + 1) return label.slice(0, capacity - ELLIPSIS.length) + ELLIPSIS;

  const kept = capacity - ELLIPSIS.length;
  const head = Math.ceil(kept / 2);
  const tail = kept - head;
  return label.slice(0, head) + ELLIPSIS + label.slice(label.length - tail);
};

/** Ceiling (px) for the value-label gutter — enough for a grouped number like "1,234,567". */
export const VALUE_LABEL_MAX_PADDING = 72;
/** Floor (px): a single digit still needs the label to clear the bar's end. */
export const VALUE_LABEL_MIN_PADDING = 14;

/**
 * Room (px) to reserve past the end of the value axis on a flipped bar chart, so the label of the
 * longest bar stays inside the SVG.
 *
 * A vertical chart gets this from the y-axis `padding.top`; flipped, the label moves to the right of
 * the bar's end with nothing holding space for it. Whenever the data max lands exactly on the axis
 * bound — which the "nice" scale produces routinely, since 10/20/50/100 are all multiples of their
 * step — the label of the biggest bar, the one read first, was clipped away entirely.
 */
export const getValueLabelPadding = (labels: string[]): number => {
  const longest = labels.reduce((max, label) => Math.max(max, label.length), 0);
  const needed = Math.ceil(longest * AXIS_CHAR_WIDTH) + AXIS_TICK_GAP;
  return Math.min(VALUE_LABEL_MAX_PADDING, Math.max(VALUE_LABEL_MIN_PADDING, needed));
};

// ── Crowded category axis ─────────────────────────────────────────────────────

/** Narrowest box (px) a wrapped x-axis label keeps; below it the axis rotates its labels instead.
 * About eight characters per line: narrower, a wrapped label breaks into a column of word stubs. */
export const X_AXIS_MIN_WRAP_WIDTH = 56;
/** Room (px) the y-axis and the chart margins take from the plot width, for the band estimate. */
const VALUE_AXIS_ALLOWANCE = 72;
/** Angle of a rotated label, in degrees below the axis. */
export const ROTATED_LABEL_ANGLE = 45;
/** Characters a rotated label keeps before it is cut from the middle; the full text is on hover. */
export const ROTATED_LABEL_MAX_CHARS = 24;
/** Ceiling (px) of the axis height a rotated set of labels reserves. */
const ROTATED_AXIS_MAX_HEIGHT = 140;

/**
 * Whether a vertical category axis rotates its labels: once each category's band leaves a wrapped
 * label less than {@link X_AXIS_MIN_WRAP_WIDTH}. Above that, wrapping keeps labels horizontal and
 * readable; below, a −45° line uses the diagonal instead of piling words into a narrow column.
 * Unknown width (first render) keeps the wrapped layout.
 */
export const shouldRotateCategoryLabels = (categoryCount: number, chartWidth?: number): boolean => {
  if (categoryCount <= 1 || chartWidth === undefined || !Number.isFinite(chartWidth) || chartWidth <= 0) {
    return false;
  }
  const band = (chartWidth - VALUE_AXIS_ALLOWANCE) / categoryCount;
  return band - AXIS_LABEL_GAP < X_AXIS_MIN_WRAP_WIDTH;
};

/** A rotated label cut to {@link ROTATED_LABEL_MAX_CHARS}, from the middle like the flipped axis. */
export const truncateRotatedLabel = (label: string): string =>
  truncateLabelToBox(label, ROTATED_LABEL_MAX_CHARS * AXIS_CHAR_WIDTH_WIDE, 1);

/** Height (px) a rotated axis reserves: the diagonal of its longest (cut) label, plus the offset. */
export const getRotatedAxisHeight = (labels: string[]): number => {
  const longest = labels.reduce((max, label) => Math.max(max, truncateRotatedLabel(label).length), 0);
  const diagonal = longest * AXIS_CHAR_WIDTH * Math.sin((ROTATED_LABEL_ANGLE * Math.PI) / 180);
  return Math.min(ROTATED_AXIS_MAX_HEIGHT, Math.ceil(diagonal) + 24);
};

// ── Legend ────────────────────────────────────────────────────────────────────

/** Room (px) one legend entry takes besides its text: the swatch, its gap and the gap to the next. */
const LEGEND_ENTRY_CHROME = 26;
/** Share of the chart's height the legend may reserve at most; more entries scroll inside it. */
export const LEGEND_MAX_HEIGHT_SHARE = 0.3;
/** Height (px) of one wrapped legend row. */
const LEGEND_ROW_HEIGHT = 20;
/**
 * Height (px) the legend reserves, from the rows its entries wrap onto at this width, capped at
 * {@link LEGEND_MAX_HEIGHT_SHARE} of the chart's height. A grouped chart can carry dozens of series ("one
 * line per source"): a fixed one-row legend overlapped the axis, an uncapped one ate the plot.
 */
export const getLegendHeight = (labels: string[], chartWidth?: number, chartHeight?: number): number => {
  if (labels.length === 0) return CHART_LEGEND_HEIGHT;
  const width = chartWidth !== undefined && Number.isFinite(chartWidth) && chartWidth > 0 ? chartWidth : 600;
  let rows = 1;
  let rowWidth = 0;
  for (const label of labels) {
    const entry = label.length * AXIS_CHAR_WIDTH + LEGEND_ENTRY_CHROME;
    if (rowWidth > 0 && rowWidth + entry > width) {
      rows += 1;
      rowWidth = 0;
    }
    rowWidth += entry;
  }
  const needed = Math.max(CHART_LEGEND_HEIGHT, rows * LEGEND_ROW_HEIGHT + 16);
  // Never more than a share of the chart: past it the legend scrolls, so the plot keeps its room.
  if (chartHeight === undefined || !Number.isFinite(chartHeight) || chartHeight <= 0) return needed;
  return Math.min(needed, Math.max(CHART_LEGEND_HEIGHT, Math.floor(chartHeight * LEGEND_MAX_HEIGHT_SHARE)));
};
