{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "stacked-area-chart",
  "type": "registry:component",
  "title": "Stacked area chart",
  "description": "Show how a total splits across series over time, stacked, as 100% shares, or as a streamgraph, with a toggleable legend, annotations, and a snapping crosshair.",
  "categories": [
    "charts"
  ],
  "dependencies": [],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/stacked-area-chart.tsx",
      "type": "registry:component",
      "target": "components/overtrue/stacked-area-chart.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/* ------------------------------------------------------------------------ */\n/* Types                                                                     */\n/* ------------------------------------------------------------------------ */\n\n/** How the series combine: stacked, normalised to 100%, centered as a streamgraph, or overlapping. */\nexport type StackedAreaStack = \"normal\" | \"expand\" | \"stream\" | \"none\";\nexport type StackedAreaCurve = \"monotone\" | \"linear\" | \"step\";\n/** An x value as it appears in the data: a number, an ISO date string, a Date, or a category label. */\nexport type StackedAreaXValue = string | number | Date;\n\nexport interface StackedAreaSeries {\n  /** Field in each row that holds this series' value. */\n  key: string;\n  /** Name in the legend and tooltip. Defaults to `key`. */\n  label?: string;\n  /** Any CSS color. Defaults to the chart palette, cycling with softer tints past five. */\n  color?: string;\n}\n\nexport interface StackedAreaReferenceLine {\n  /** Value on the y axis. Drawn in normal and overlapping modes, where the axis is in value units. */\n  y: number;\n  label?: string;\n  color?: string;\n}\n\nexport interface StackedAreaAnnotation {\n  /** Where the marker sits, in the same form as the index values. */\n  x: StackedAreaXValue;\n  label: string;\n  color?: string;\n}\n\n/** One series at one point, as listed in the tooltip. */\nexport interface StackedAreaItem {\n  key: string;\n  label: string;\n  color: string;\n  value: number;\n  /** Share of the visible total at this point (or over the range, in a summary), 0–1. */\n  share: number;\n}\n\n/** The point under the crosshair, passed to `renderTooltip` and `onHover`. */\nexport interface StackedAreaPoint {\n  /** Position in the sorted data. */\n  index: number;\n  /** A Date on time axes, otherwise the number or label from the data. */\n  x: StackedAreaXValue;\n  /** The x value formatted for the tooltip. */\n  label: string;\n  /** The original row. */\n  row: Record<string, unknown>;\n  /** Sum of the visible series. */\n  total: number;\n  /** Visible series, top of the stack first. */\n  items: StackedAreaItem[];\n  /** Annotations that fall on this point. */\n  annotations: StackedAreaAnnotation[];\n}\n\n/** Totals across the whole range, passed to a `header` function. */\nexport interface StackedAreaSummary {\n  /** Sum of every visible series over every point. */\n  total: number;\n  /** Visible total at the first and the last point. */\n  first: number;\n  last: number;\n  /** Every series with its total over the range and its share of `total`, in legend order. */\n  series: (StackedAreaItem & { hidden: boolean })[];\n  /** Number of points. */\n  count: number;\n  /** The chart's value formatter. */\n  format: (value: number) => string;\n}\n\nexport type StackedAreaXFormatter = (\n  value: StackedAreaXValue,\n  context: \"axis\" | \"tooltip\",\n) => string;\n\nexport interface StackedAreaChartProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"children\" | \"color\"\n> {\n  /** Rows, one per x value. Missing or negative values count as zero. */\n  data: Record<string, unknown>[];\n  /** Field holding the x value: numbers, ISO date strings, Dates, or category labels. */\n  index: string;\n  /** Series to stack, bottom first. */\n  series: StackedAreaSeries[];\n  stack?: StackedAreaStack;\n  curve?: StackedAreaCurve;\n  /** Plot height in pixels. Defaults to 280. */\n  height?: number;\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Controls placed at the top right. */\n  actions?: React.ReactNode;\n  /** Content under the title, such as a headline total. A function receives the totals for the visible series. */\n  header?: React.ReactNode | ((summary: StackedAreaSummary) => React.ReactNode);\n  /** Formats values in the tooltip, legend, and summary. Defaults to compact numbers from 10,000. */\n  valueFormatter?: (value: number) => string;\n  /** Formats y axis ticks. Defaults to compact numbers such as 2.4M, or percentages when expanded. */\n  axisFormatter?: (value: number) => string;\n  /** Formats x values on the axis and in the tooltip. Dates default to Intl formats matched to the spacing. */\n  xFormatter?: StackedAreaXFormatter;\n  /** Short name of the y axis, shown above it. */\n  yLabel?: string;\n  referenceLines?: StackedAreaReferenceLine[];\n  /** Thin vertical markers with a label, for events such as a deploy. */\n  annotations?: StackedAreaAnnotation[];\n  /** Keys of hidden series. Pass with `onHiddenSeriesChange` to control the legend. */\n  hiddenSeries?: string[];\n  defaultHiddenSeries?: string[];\n  onHiddenSeriesChange?: (hidden: string[]) => void;\n  /** Show the interactive legend. Defaults to true. */\n  showLegend?: boolean;\n  legendPosition?: \"top\" | \"bottom\";\n  /** Replaces the tooltip content. */\n  renderTooltip?: (point: StackedAreaPoint) => React.ReactNode;\n  /** Called when the crosshair moves to a point, and with null when it leaves. */\n  onHover?: (point: StackedAreaPoint | null) => void;\n  /** Tween between states when series toggle, the stack mode changes, or data updates. Defaults to true. */\n  animate?: boolean;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Formatting                                                                */\n/* ------------------------------------------------------------------------ */\n\nconst DAY = 86_400_000;\nconst tidy = (value: number) => +value.toPrecision(12);\nconst lowerK = (text: string) => text.replace(/K$/, \"k\");\nconst compactAxis = new Intl.NumberFormat(\"en-US\", {\n  notation: \"compact\",\n  maximumFractionDigits: 1,\n});\nconst compactValue = new Intl.NumberFormat(\"en-US\", {\n  notation: \"compact\",\n  maximumSignificantDigits: 3,\n});\nconst grouped = new Intl.NumberFormat(\"en-US\", { maximumFractionDigits: 2 });\n\nfunction defaultValueFormatter(value: number) {\n  if (!Number.isFinite(value)) return \"—\";\n  return Math.abs(value) >= 10_000\n    ? lowerK(compactValue.format(value))\n    : grouped.format(value);\n}\n\nfunction defaultAxisFormatter(value: number) {\n  return value === 0 ? \"0\" : lowerK(compactAxis.format(value));\n}\n\nfunction percentAxis(value: number) {\n  return `${tidy(value * 100)}%`;\n}\n\nfunction formatShare(share: number, digits = 1) {\n  const pct = share * 100;\n  if (!Number.isFinite(pct) || pct === 0) return \"0%\";\n  if (pct < 0.1) return \"<0.1%\";\n  return `${pct.toFixed(digits)}%`;\n}\n\n// \"Atlas Large hidden\" reads better than a pressed state for screen readers.\nconst sentence = (parts: string[]) => parts.filter(Boolean).join(\" \");\n\n/* ------------------------------------------------------------------------ */\n/* X values                                                                  */\n/* ------------------------------------------------------------------------ */\n\ntype XKind = \"time\" | \"number\" | \"category\";\n\nconst DATE_ONLY = /^(\\d{4})-(\\d{2})(?:-(\\d{2}))?$/;\nconst DATE_TIME =\n  /^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?(?:Z|[+-]\\d{2}:?\\d{2})?$/;\n\n/** Date-only strings are local calendar days, so \"2026-10-03\" never renders as Oct 2. */\nfunction toTime(raw: unknown): number | null {\n  if (raw instanceof Date) {\n    const t = raw.getTime();\n    return Number.isNaN(t) ? null : t;\n  }\n  if (typeof raw !== \"string\") return null;\n  const day = DATE_ONLY.exec(raw);\n  if (day) return new Date(+day[1], +day[2] - 1, day[3] ? +day[3] : 1).getTime();\n  if (DATE_TIME.test(raw)) {\n    const t = Date.parse(raw.replace(\" \", \"T\"));\n    return Number.isNaN(t) ? null : t;\n  }\n  return null;\n}\n\nfunction xKindOf(values: unknown[]): XKind {\n  if (!values.length) return \"category\";\n  if (values.every((v) => typeof v === \"number\" && Number.isFinite(v)))\n    return \"number\";\n  if (values.every((v) => toTime(v) !== null)) return \"time\";\n  return \"category\";\n}\n\nfunction makeDateFormatter(step: number, spansYears: boolean) {\n  const f = (options: Intl.DateTimeFormatOptions) =>\n    new Intl.DateTimeFormat(\"en-US\", options);\n  if (step < DAY) {\n    const time = f({ hour: \"2-digit\", minute: \"2-digit\", hourCycle: \"h23\" });\n    const day = f({ month: \"short\", day: \"numeric\" });\n    const tip = f({\n      weekday: \"short\",\n      month: \"short\",\n      day: \"numeric\",\n      hour: \"2-digit\",\n      minute: \"2-digit\",\n      hourCycle: \"h23\",\n    });\n    // Midnight ticks name the day, so a multi-day axis stays readable.\n    return (d: Date, c: \"axis\" | \"tooltip\") =>\n      c === \"tooltip\"\n        ? tip.format(d)\n        : d.getHours() === 0 && d.getMinutes() === 0\n          ? day.format(d)\n          : time.format(d);\n  }\n  if (step < 28 * DAY) {\n    const axis = f({ month: \"short\", day: \"numeric\" });\n    const tip = f({\n      weekday: \"short\",\n      month: \"short\",\n      day: \"numeric\",\n      ...(spansYears ? { year: \"numeric\" } : {}),\n    });\n    return (d: Date, c: \"axis\" | \"tooltip\") =>\n      (c === \"axis\" ? axis : tip).format(d);\n  }\n  if (step < 360 * DAY) {\n    const axis = f(\n      spansYears ? { month: \"short\", year: \"2-digit\" } : { month: \"short\" },\n    );\n    const tip = f({ month: \"long\", year: \"numeric\" });\n    return (d: Date, c: \"axis\" | \"tooltip\") =>\n      (c === \"axis\" ? axis : tip).format(d);\n  }\n  const year = f({ year: \"numeric\" });\n  return (d: Date) => year.format(d);\n}\n\n/* ------------------------------------------------------------------------ */\n/* Model                                                                     */\n/* ------------------------------------------------------------------------ */\n\ninterface Model {\n  kind: XKind;\n  rows: Record<string, unknown>[];\n  /** Numeric x positions: epoch ms, numbers, or the row index for categories. */\n  xs: number[];\n  /** Parsed x values: Dates on time axes. */\n  xValues: StackedAreaXValue[];\n  /** Identity of each point, used to match points across updates. */\n  keys: string[];\n  /** Clean values per series and point. */\n  values: number[][];\n  /** Typical spacing between points, in x units. */\n  step: number;\n}\n\nfunction buildModel(\n  data: Record<string, unknown>[],\n  index: string,\n  keys: string[],\n): Model {\n  const kind = xKindOf(data.map((row) => row?.[index]));\n  const items = data.map((row, i) => {\n    const raw = row?.[index];\n    if (kind === \"number\") return { row, x: raw as number, value: raw as number };\n    if (kind === \"time\") {\n      const t = toTime(raw)!;\n      return { row, x: t, value: new Date(t) as StackedAreaXValue };\n    }\n    return { row, x: i, value: String(raw ?? \"\") as StackedAreaXValue };\n  });\n  if (kind !== \"category\") items.sort((a, b) => a.x - b.x);\n  const xs = items.map((item) => item.x);\n  const diffs: number[] = [];\n  for (let i = 1; i < xs.length; i++)\n    if (xs[i] > xs[i - 1]) diffs.push(xs[i] - xs[i - 1]);\n  diffs.sort((a, b) => a - b);\n  return {\n    kind,\n    rows: items.map((item) => item.row ?? {}),\n    xs,\n    xValues: items.map((item) => item.value),\n    keys:\n      kind === \"category\" ? items.map((_, i) => String(i)) : xs.map(String),\n    values: keys.map((key) =>\n      items.map((item) => {\n        const v = Number(item.row?.[key]);\n        return Number.isFinite(v) && v > 0 ? v : 0;\n      }),\n    ),\n    step: diffs.length ? diffs[diffs.length >> 1] : 1,\n  };\n}\n\n/* ------------------------------------------------------------------------ */\n/* Scales                                                                    */\n/* ------------------------------------------------------------------------ */\n\nfunction niceStep(raw: number) {\n  if (!(raw > 0)) return 1;\n  const magnitude = 10 ** Math.floor(Math.log10(raw));\n  const r = raw / magnitude;\n  return (\n    (r <= 1 ? 1 : r <= 2 ? 2 : r <= 2.5 ? 2.5 : r <= 5 ? 5 : 10) * magnitude\n  );\n}\n\n/** Ticks from zero: three to `most` intervals of 1, 2, 2.5 or 5 × 10ⁿ, with the least wasted headroom. */\nfunction niceScale(max: number, most: number) {\n  if (!(max > 0)) return { hi: 1, ticks: [0, 0.5, 1] };\n  const target = max * 1.02;\n  const exponent = Math.floor(Math.log10(target));\n  let best: { step: number; count: number; score: number } | null = null;\n  for (let e = exponent - 2; e <= exponent + 1; e++)\n    for (const m of [1, 2, 2.5, 5]) {\n      const step = m * 10 ** e;\n      const count = Math.ceil(target / step - 1e-9);\n      if (count < 3 || count > most) continue;\n      const hi = count * step;\n      const score =\n        (hi - target) / hi + Math.abs(count - 4) * 0.04 + (m === 2.5 ? 0.04 : 0);\n      if (!best || score < best.score) best = { step, count, score };\n    }\n  const step = best?.step ?? niceStep(target / 4);\n  const count = best?.count ?? Math.max(1, Math.ceil(target / step - 1e-9));\n  return {\n    hi: tidy(count * step),\n    ticks: Array.from({ length: count + 1 }, (_, i) => tidy(i * step)),\n  };\n}\n\n/* ------------------------------------------------------------------------ */\n/* Frames: the stacked geometry in data units, tweened between states        */\n/* ------------------------------------------------------------------------ */\n\ninterface Frame {\n  keys: string[];\n  xs: number[];\n  series: string[];\n  /** Lower and upper edge per series and point, in y units. */\n  y0: number[][];\n  y1: number[][];\n  /** 1 when a series is shown, 0 when hidden; fractional mid-tween. */\n  weight: number[];\n  x0: number;\n  x1: number;\n  lo: number;\n  hi: number;\n}\n\nfunction stackFrame(\n  model: Model,\n  seriesKeys: string[],\n  visible: boolean[],\n  stack: StackedAreaStack,\n  lo: number,\n  hi: number,\n): Frame {\n  const n = model.xs.length;\n  const y0 = seriesKeys.map(() => new Array<number>(n).fill(0));\n  const y1 = seriesKeys.map(() => new Array<number>(n).fill(0));\n  for (let j = 0; j < n; j++) {\n    let total = 0;\n    for (let s = 0; s < seriesKeys.length; s++)\n      if (visible[s]) total += model.values[s][j];\n    if (stack === \"none\") {\n      for (let s = 0; s < seriesKeys.length; s++)\n        y1[s][j] = visible[s] ? model.values[s][j] : 0;\n      continue;\n    }\n    const scale = stack === \"expand\" ? (total > 0 ? 1 / total : 0) : 1;\n    let running = stack === \"stream\" ? -total / 2 : 0;\n    for (let s = 0; s < seriesKeys.length; s++) {\n      y0[s][j] = running;\n      running += visible[s] ? model.values[s][j] * scale : 0;\n      y1[s][j] = running;\n    }\n  }\n  const first = model.xs[0] ?? 0;\n  const last = model.xs[n - 1] ?? 1;\n  const pad = n > 1 ? 0 : model.step / 2 || 0.5;\n  return {\n    keys: model.keys,\n    xs: model.xs,\n    series: seriesKeys,\n    y0,\n    y1,\n    weight: visible.map((v) => (v ? 1 : 0)),\n    x0: first - pad,\n    x1: last + pad,\n    lo,\n    hi,\n  };\n}\n\nfunction framesEqual(a: Frame, b: Frame) {\n  if (a === b) return true;\n  const same = (p: number, q: number) => Math.abs(p - q) < 1e-9;\n  if (\n    a.keys.length !== b.keys.length ||\n    a.series.length !== b.series.length ||\n    !same(a.x0, b.x0) ||\n    !same(a.x1, b.x1) ||\n    !same(a.lo, b.lo) ||\n    !same(a.hi, b.hi)\n  )\n    return false;\n  for (let i = 0; i < a.keys.length; i++)\n    if (a.keys[i] !== b.keys[i] || !same(a.xs[i], b.xs[i])) return false;\n  for (let s = 0; s < a.series.length; s++) {\n    if (a.series[s] !== b.series[s] || a.weight[s] !== b.weight[s]) return false;\n    for (let i = 0; i < a.keys.length; i++)\n      if (!same(a.y0[s][i], b.y0[s][i]) || !same(a.y1[s][i], b.y1[s][i]))\n        return false;\n  }\n  return true;\n}\n\n/**\n * Interpolates two frames. Points are matched by identity, so a sliding window keeps\n * every shared point still and glides the x domain instead of morphing the shape.\n */\nfunction lerpFrame(a: Frame, b: Frame, t: number): Frame {\n  const mix = (p: number, q: number) => p + (q - p) * t;\n  const seriesIndex = new Map(a.series.map((key, i) => [key, i]));\n  let keys = b.keys;\n  let xs: number[];\n  let fromIndex: number[];\n  let toIndex: number[];\n  if (\n    a.keys.length === b.keys.length &&\n    a.keys.every((key, i) => key === b.keys[i])\n  ) {\n    xs = b.xs.map((x, i) => mix(a.xs[i], x));\n    fromIndex = toIndex = b.keys.map((_, i) => i);\n  } else {\n    const inA = new Map(a.keys.map((key, i) => [key, i]));\n    const inB = new Map(b.keys.map((key, i) => [key, i]));\n    const xOf = (key: string) =>\n      inB.has(key) ? b.xs[inB.get(key)!] : a.xs[inA.get(key)!];\n    keys = [...new Set([...a.keys, ...b.keys])].sort((p, q) => xOf(p) - xOf(q));\n    xs = keys.map(xOf);\n    fromIndex = keys.map((key) => inA.get(key) ?? -1);\n    toIndex = keys.map((key) => inB.get(key) ?? -1);\n  }\n  const y0: number[][] = [];\n  const y1: number[][] = [];\n  const weight: number[] = [];\n  b.series.forEach((key, s) => {\n    const sa = seriesIndex.get(key) ?? -1;\n    const lower: number[] = [];\n    const upper: number[] = [];\n    keys.forEach((_, j) => {\n      const ia = fromIndex[j];\n      const ib = toIndex[j];\n      const to0 = ib >= 0 ? b.y0[s][ib] : null;\n      const to1 = ib >= 0 ? b.y1[s][ib] : null;\n      // A new series grows from its own base; a leaving point holds still.\n      const from0 = sa >= 0 && ia >= 0 ? a.y0[sa][ia] : (to0 ?? 0);\n      const from1 = sa >= 0 && ia >= 0 ? a.y1[sa][ia] : (to0 ?? 0);\n      lower.push(mix(from0, to0 ?? from0));\n      upper.push(mix(from1, to1 ?? from1));\n    });\n    y0.push(lower);\n    y1.push(upper);\n    weight.push(mix(sa >= 0 ? a.weight[sa] : 0, b.weight[s]));\n  });\n  return {\n    keys,\n    xs,\n    series: b.series,\n    y0,\n    y1,\n    weight,\n    x0: mix(a.x0, b.x0),\n    x1: mix(a.x1, b.x1),\n    lo: mix(a.lo, b.lo),\n    hi: mix(a.hi, b.hi),\n  };\n}\n\n/* ------------------------------------------------------------------------ */\n/* Curves                                                                    */\n/* ------------------------------------------------------------------------ */\n\nconst r2 = (value: number) => Math.round(value * 100) / 100;\n\n/** Steffen's monotone tangents: no overshoot between points, so stacked edges never cross. */\nfunction monotoneTangents(xs: number[], ys: number[]) {\n  const n = xs.length;\n  const m = new Array<number>(n).fill(0);\n  if (n < 2) return m;\n  const h: number[] = [];\n  const d: number[] = [];\n  for (let i = 0; i < n - 1; i++) {\n    h.push(xs[i + 1] - xs[i]);\n    d.push(h[i] ? (ys[i + 1] - ys[i]) / h[i] : 0);\n  }\n  if (n === 2) {\n    m[0] = m[1] = d[0];\n    return m;\n  }\n  for (let i = 1; i < n - 1; i++) {\n    const s0 = d[i - 1];\n    const s1 = d[i];\n    if (s0 * s1 <= 0) continue;\n    const p = (s0 * h[i] + s1 * h[i - 1]) / (h[i - 1] + h[i] || 1);\n    m[i] =\n      Math.sign(s0) *\n      Math.min(2 * Math.abs(s0), 2 * Math.abs(s1), Math.abs(p));\n  }\n  // One-sided ends keep the tangent within the first and last secant.\n  m[0] = (3 * d[0] - m[1]) / 2;\n  m[n - 1] = (3 * d[n - 2] - m[n - 2]) / 2;\n  return m;\n}\n\n/** Path commands from the first point to the last (or back), without the opening move. */\nfunction edge(\n  xs: number[],\n  ys: number[],\n  curve: StackedAreaCurve,\n  reverse: boolean,\n) {\n  const n = xs.length;\n  if (n < 2) return \"\";\n  let out = \"\";\n  if (curve === \"linear\") {\n    if (reverse)\n      for (let i = n - 2; i >= 0; i--) out += `L${r2(xs[i])} ${r2(ys[i])}`;\n    else for (let i = 1; i < n; i++) out += `L${r2(xs[i])} ${r2(ys[i])}`;\n    return out;\n  }\n  if (curve === \"step\") {\n    if (reverse)\n      for (let i = n - 2; i >= 0; i--) {\n        const mid = (xs[i] + xs[i + 1]) / 2;\n        out += `H${r2(mid)}V${r2(ys[i])}H${r2(xs[i])}`;\n      }\n    else\n      for (let i = 0; i < n - 1; i++) {\n        const mid = (xs[i] + xs[i + 1]) / 2;\n        out += `H${r2(mid)}V${r2(ys[i + 1])}H${r2(xs[i + 1])}`;\n      }\n    return out;\n  }\n  const m = monotoneTangents(xs, ys);\n  const segment = (i: number) => {\n    const h = (xs[i + 1] - xs[i]) / 3;\n    return [\n      xs[i] + h,\n      ys[i] + m[i] * h,\n      xs[i + 1] - h,\n      ys[i + 1] - m[i + 1] * h,\n    ];\n  };\n  if (reverse)\n    for (let i = n - 2; i >= 0; i--) {\n      const [c1x, c1y, c2x, c2y] = segment(i);\n      out += `C${r2(c2x)} ${r2(c2y)} ${r2(c1x)} ${r2(c1y)} ${r2(xs[i])} ${r2(ys[i])}`;\n    }\n  else\n    for (let i = 0; i < n - 1; i++) {\n      const [c1x, c1y, c2x, c2y] = segment(i);\n      out += `C${r2(c1x)} ${r2(c1y)} ${r2(c2x)} ${r2(c2y)} ${r2(xs[i + 1])} ${r2(ys[i + 1])}`;\n    }\n  return out;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Hooks                                                                     */\n/* ------------------------------------------------------------------------ */\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (onChange) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", onChange);\n      return () => query.removeEventListener(\"change\", onChange);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\nfunction useControllable<T>(\n  value: T | undefined,\n  defaultValue: T,\n  onChange?: (value: T) => void,\n) {\n  const [inner, setInner] = React.useState(defaultValue);\n  const controlled = value !== undefined;\n  const set = React.useCallback(\n    (next: T) => {\n      if (!controlled) setInner(next);\n      onChange?.(next);\n    },\n    [controlled, onChange],\n  );\n  return [controlled ? value : inner, set] as const;\n}\n\nconst easeOut = (t: number) => 1 - (1 - t) ** 3;\nconst easeInOut = (t: number) =>\n  t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2;\n\n/** Default palette: the five chart colors, then softer tints of the same five. */\nfunction paletteColor(i: number) {\n  const base = `var(--color-chart-${(i % 5) + 1})`;\n  const round = Math.floor(i / 5);\n  return round === 0\n    ? base\n    : `color-mix(in oklab, ${base} ${Math.max(40, 100 - round * 28)}%, var(--color-card))`;\n}\n\nconst focusRing =\n  \"outline-none focus-visible:ring-2 focus-visible:ring-primary/30 focus-visible:shadow-[0_0_0_4px_color-mix(in_oklab,var(--color-primary)_10%,transparent)]\";\nconst gridColor = \"color-mix(in oklab, var(--color-foreground) 7%, transparent)\";\nconst baseColor = \"color-mix(in oklab, var(--color-foreground) 14%, transparent)\";\n\n/* ------------------------------------------------------------------------ */\n/* StackedAreaChart                                                          */\n/* ------------------------------------------------------------------------ */\n\n/**\n * A composition over time: stacked, normalised, streamgraph, or overlapping areas with\n * an interactive legend, a snapping crosshair, annotations, and tweened re-stacking.\n */\nexport function StackedAreaChart({\n  data,\n  index,\n  series,\n  stack = \"normal\",\n  curve = \"monotone\",\n  height = 280,\n  title,\n  description,\n  actions,\n  header,\n  valueFormatter = defaultValueFormatter,\n  axisFormatter,\n  xFormatter,\n  yLabel,\n  referenceLines,\n  annotations,\n  hiddenSeries,\n  defaultHiddenSeries = [],\n  onHiddenSeriesChange,\n  showLegend = true,\n  legendPosition = \"bottom\",\n  renderTooltip,\n  onHover,\n  animate = true,\n  className,\n  ...props\n}: StackedAreaChartProps) {\n  const id = React.useId().replace(/:/g, \"\");\n  const reduced = useReducedMotion();\n  const motion = animate && !reduced;\n\n  const [hidden, setHidden] = useControllable(\n    hiddenSeries,\n    defaultHiddenSeries,\n    onHiddenSeriesChange,\n  );\n  const hiddenSet = React.useMemo(() => new Set(hidden), [hidden]);\n\n  // Geometry depends only on series keys, so inline series arrays never restart a tween.\n  const seriesSignature = series.map((s) => s.key).join(\"\\u0000\");\n  const seriesKeys = React.useMemo(\n    () => (seriesSignature ? seriesSignature.split(\"\\u0000\") : []),\n    [seriesSignature],\n  );\n  const meta = series.map((s, i) => ({\n    key: s.key,\n    label: s.label ?? s.key,\n    color: s.color ?? paletteColor(i),\n  }));\n\n  const model = React.useMemo(\n    () => buildModel(data, index, seriesKeys),\n    [data, index, seriesKeys],\n  );\n  const n = model.xs.length;\n  const visible = seriesKeys.map((key) => !hiddenSet.has(key));\n  const visibleSignature = visible.map(Number).join(\"\");\n  const anyVisible = visible.some(Boolean);\n\n  /* ------------------------------------------------------------- format */\n\n  const formatX = React.useMemo(() => {\n    if (xFormatter) return xFormatter;\n    if (model.kind === \"time\") {\n      const first = model.xs[0] ?? 0;\n      const last = model.xs[n - 1] ?? 0;\n      const date = makeDateFormatter(\n        model.step,\n        new Date(first).getFullYear() !== new Date(last).getFullYear(),\n      );\n      return (value: StackedAreaXValue, context: \"axis\" | \"tooltip\") =>\n        date(value instanceof Date ? value : new Date(value), context);\n    }\n    if (model.kind === \"number\")\n      return (value: StackedAreaXValue) =>\n        typeof value === \"number\" ? grouped.format(value) : String(value);\n    return (value: StackedAreaXValue) => String(value);\n  }, [xFormatter, model, n]);\n\n  const formatTick = React.useMemo(\n    () =>\n      axisFormatter ?? (stack === \"expand\" ? percentAxis : defaultAxisFormatter),\n    [axisFormatter, stack],\n  );\n\n  /* -------------------------------------------------------------- scale */\n\n  const refs = React.useMemo(\n    () =>\n      (referenceLines ?? []).filter(\n        (line) => Number.isFinite(line.y) && (stack === \"normal\" || stack === \"none\"),\n      ),\n    [referenceLines, stack],\n  );\n\n  const scale = React.useMemo(() => {\n    const vis = visibleSignature.split(\"\").map((v) => v === \"1\");\n    let peak = 0;\n    for (let j = 0; j < n; j++) {\n      let total = 0;\n      for (let s = 0; s < seriesKeys.length; s++) {\n        if (!vis[s]) continue;\n        const v = model.values[s][j];\n        if (stack === \"none\") peak = Math.max(peak, v);\n        else total += v;\n      }\n      peak = Math.max(peak, total);\n    }\n    if (stack === \"expand\")\n      return { lo: 0, hi: 1, ticks: [0, 0.25, 0.5, 0.75, 1], peak };\n    if (stack === \"stream\") {\n      const half = (peak || 1) / 2;\n      return { lo: -half * 1.06, hi: half * 1.06, ticks: [0], peak };\n    }\n    for (const line of refs) peak = Math.max(peak, line.y);\n    const nice = niceScale(peak, height < 200 ? 4 : 5);\n    return { lo: 0, hi: nice.hi, ticks: nice.ticks, peak };\n  }, [model, n, seriesKeys, visibleSignature, stack, refs, height]);\n\n  const target = React.useMemo(\n    () =>\n      stackFrame(\n        model,\n        seriesKeys,\n        visibleSignature.split(\"\").map((v) => v === \"1\"),\n        stack,\n        scale.lo,\n        scale.hi,\n      ),\n    [model, seriesKeys, visibleSignature, stack, scale],\n  );\n\n  /* ------------------------------------------------------------- motion */\n\n  const [tween, setTween] = React.useState<Frame | null>(null);\n  const shownRef = React.useRef<Frame>(target);\n  const modelRef = React.useRef(model);\n  React.useLayoutEffect(() => {\n    const from = shownRef.current;\n    const dataChanged = modelRef.current !== model;\n    modelRef.current = model;\n    if (from === target) return;\n    if (!motion || framesEqual(from, target)) {\n      shownRef.current = target;\n      setTween(null);\n      return;\n    }\n    // Data updates glide a little longer than toggles, which should feel immediate.\n    const duration = dataChanged ? 460 : 320;\n    const ease = dataChanged ? easeInOut : easeOut;\n    const start = performance.now();\n    setTween(from);\n    let frame = requestAnimationFrame(function step(now) {\n      const t = Math.min(1, (now - start) / duration);\n      if (t >= 1) {\n        shownRef.current = target;\n        setTween(null);\n        return;\n      }\n      const next = lerpFrame(from, target, ease(t));\n      shownRef.current = next;\n      setTween(next);\n      frame = requestAnimationFrame(step);\n    });\n    return () => cancelAnimationFrame(frame);\n  }, [target, model, motion]);\n  const shown = tween ?? target;\n\n  /* ------------------------------------------------------------- layout */\n\n  const plotRef = React.useRef<HTMLDivElement>(null);\n  const [width, setWidth] = React.useState(0);\n  React.useLayoutEffect(() => {\n    const el = plotRef.current;\n    if (!el) return;\n    const measure = () => setWidth(Math.round(el.clientWidth));\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n  const W = width || 640;\n  const H = Math.max(96, height);\n\n  // Annotation labels stack into lanes above the plot only when they would collide.\n  const marks = React.useMemo(() => {\n    if (!annotations?.length || !n) return [];\n    const lanes: number[] = [];\n    const span = target.x1 - target.x0 || 1;\n    return annotations\n      .map((note) => {\n        let x: number | null = null;\n        if (model.kind === \"time\") x = toTime(note.x);\n        else if (model.kind === \"number\")\n          x = typeof note.x === \"number\" ? note.x : Number(note.x);\n        else {\n          const i = model.xValues.findIndex((v) => v === String(note.x));\n          x = i >= 0 ? i : null;\n        }\n        if (x == null || !Number.isFinite(x)) return null;\n        // The nearest point, so the tooltip can repeat the note.\n        let nearest = 0;\n        for (let i = 1; i < n; i++)\n          if (Math.abs(model.xs[i] - x) < Math.abs(model.xs[nearest] - x))\n            nearest = i;\n        return { note, x, nearest, fraction: (x - target.x0) / span };\n      })\n      .filter((m): m is NonNullable<typeof m> => m !== null)\n      .filter((m) => m.fraction >= -0.001 && m.fraction <= 1.001)\n      .sort((a, b) => a.x - b.x)\n      .map((m) => {\n        const w = Math.min(W, m.note.label.length * 6.3 + 24);\n        const px = m.fraction * W;\n        const flip = px + w > W && px - w >= 0;\n        const left = flip ? px - w : Math.max(0, Math.min(px, W - w));\n        let lane = lanes.findIndex((right) => right + 6 <= left);\n        if (lane < 0) lane = lanes.push(0) - 1;\n        lanes[lane] = left + w;\n        return { ...m, w, left, lane, flip };\n      });\n  }, [annotations, n, model, target.x0, target.x1, W]);\n  const laneCount = marks.length\n    ? Math.max(...marks.map((m) => m.lane)) + 1\n    : 0;\n  const padTop = 8 + laneCount * 26;\n  const padBottom = 1;\n  const plotH = H - padTop - padBottom;\n\n  const X = (x: number) => ((x - shown.x0) / (shown.x1 - shown.x0 || 1)) * W;\n  const entranceBase =\n    padTop + ((scale.hi - (stack === \"stream\" ? 0 : scale.lo)) / (scale.hi - scale.lo || 1)) * plotH;\n  const Y = (y: number) =>\n    padTop + ((shown.hi - y) / (shown.hi - shown.lo || 1)) * plotH;\n\n  const geometry = React.useMemo(() => {\n    const px = shown.xs.map(\n      (x) => ((x - shown.x0) / (shown.x1 - shown.x0 || 1)) * W,\n    );\n    const py = (y: number) =>\n      padTop + ((shown.hi - y) / (shown.hi - shown.lo || 1)) * plotH;\n    return shown.series.map((key, s) => {\n      const top = shown.y1[s].map(py);\n      const bottom = shown.y0[s].map(py);\n      let thickness = 0;\n      for (let j = 0; j < top.length; j++)\n        thickness = Math.max(thickness, bottom[j] - top[j]);\n      if (!px.length) return { key, area: \"\", line: \"\", base: \"\", thickness };\n      const single = px.length === 1;\n      const xs = single ? [px[0] - W / 2, px[0] + W / 2] : px;\n      const t = single ? [top[0], top[0]] : top;\n      const b = single ? [bottom[0], bottom[0]] : bottom;\n      const head = `M${r2(xs[0])} ${r2(t[0])}${edge(xs, t, curve, false)}`;\n      return {\n        key,\n        line: head,\n        base: `M${r2(xs[0])} ${r2(b[0])}${edge(xs, b, curve, false)}`,\n        area: `${head}L${r2(xs[xs.length - 1])} ${r2(b[b.length - 1])}${edge(xs, b, curve, true)}Z`,\n        thickness,\n      };\n    });\n  }, [shown, W, padTop, plotH, curve]);\n\n  /* -------------------------------------------------------------- ticks */\n\n  const yTicks = scale.ticks;\n  const yTickLabels = stack === \"stream\" ? [] : yTicks.map(formatTick);\n\n  const xTicks = React.useMemo(() => {\n    if (!n) return [] as { x: number; label: string }[];\n    const labelWidth = 64;\n    const room = Math.max(2, Math.floor(W / labelWidth));\n    if (model.kind === \"number\") {\n      const lo = model.xs[0];\n      const hi = model.xs[n - 1];\n      if (hi <= lo) return [{ x: lo, label: formatX(lo, \"axis\") }];\n      const step = niceStep((hi - lo) / Math.max(1, room - 1));\n      const ticks: { x: number; label: string }[] = [];\n      for (\n        let v = Math.ceil(lo / step - 1e-9) * step;\n        v <= hi + step * 1e-6;\n        v += step\n      )\n        ticks.push({ x: tidy(v), label: formatX(tidy(v), \"axis\") });\n      return ticks;\n    }\n    // Every k-th point. Sub-day axes land on round hours; others count back from the\n    // latest point so the newest value is always labelled.\n    const subDay = model.kind === \"time\" && model.step < DAY;\n    const steps = subDay\n      ? [1, 2, 3, 4, 6, 8, 12, 24, 48, 72, 168]\n      : model.kind === \"time\" && model.step >= 28 * DAY\n        ? [1, 2, 3, 6, 12, 24, 60]\n        : [1, 2, 3, 4, 5, 7, 10, 14, 15, 20, 28, 30, 50, 60, 100];\n    const k =\n      steps.find((step) => Math.floor((n - 1) / step) + 1 <= room) ??\n      Math.ceil(n / room);\n    let phase = (n - 1) % k;\n    if (subDay) {\n      const span = k * model.step;\n      for (let o = 0; o < Math.min(k, n); o++) {\n        const d = new Date(model.xs[o]);\n        const sinceMidnight =\n          model.xs[o] - new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();\n        if (Math.round(sinceMidnight) % Math.round(span) === 0) {\n          phase = o;\n          break;\n        }\n      }\n    }\n    const ticks: { x: number; label: string }[] = [];\n    for (let i = phase; i < n; i += k)\n      ticks.push({ x: model.xs[i], label: formatX(model.xValues[i], \"axis\") });\n    return ticks;\n  }, [n, model, W, formatX]);\n\n  /* ---------------------------------------------------------- summaries */\n\n  const summary = React.useMemo<StackedAreaSummary>(() => {\n    const totals = seriesKeys.map((_, s) =>\n      model.values[s].reduce((sum, v) => sum + v, 0),\n    );\n    const vis = visibleSignature.split(\"\").map((v) => v === \"1\");\n    const total = totals.reduce((sum, v, s) => sum + (vis[s] ? v : 0), 0);\n    const at = (j: number) =>\n      j < 0\n        ? 0\n        : seriesKeys.reduce(\n            (sum, _, s) => sum + (vis[s] ? model.values[s][j] : 0),\n            0,\n          );\n    return {\n      total,\n      first: n ? at(0) : 0,\n      last: n ? at(n - 1) : 0,\n      count: n,\n      format: valueFormatter,\n      series: seriesKeys.map((key, s) => ({\n        key,\n        label: series[s]?.label ?? key,\n        color: series[s]?.color ?? paletteColor(s),\n        value: totals[s],\n        share: vis[s] && total > 0 ? totals[s] / total : 0,\n        hidden: !vis[s],\n      })),\n    };\n  }, [model, n, seriesKeys, visibleSignature, valueFormatter, series]);\n\n  const pointAt = React.useCallback(\n    (j: number): StackedAreaPoint => {\n      const items: StackedAreaItem[] = [];\n      let total = 0;\n      for (let s = 0; s < seriesKeys.length; s++)\n        if (visible[s]) total += model.values[s][j];\n      for (let s = seriesKeys.length - 1; s >= 0; s--) {\n        if (!visible[s]) continue;\n        const value = model.values[s][j];\n        items.push({\n          key: seriesKeys[s],\n          label: series[s]?.label ?? seriesKeys[s],\n          color: series[s]?.color ?? paletteColor(s),\n          value,\n          share: total > 0 ? value / total : 0,\n        });\n      }\n      return {\n        index: j,\n        x: model.xValues[j],\n        label: formatX(model.xValues[j], \"tooltip\"),\n        row: model.rows[j],\n        total,\n        items,\n        annotations: marks.filter((m) => m.nearest === j).map((m) => m.note),\n      };\n    },\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [model, seriesKeys, visibleSignature, series, formatX, marks],\n  );\n\n  /* -------------------------------------------------------- interaction */\n\n  const [active, setActive] = React.useState<number | null>(null);\n  const [pointerBand, setPointerBand] = React.useState<string | null>(null);\n  const [hovered, setHighlight] = React.useState<string | null>(null);\n  // A series hidden while hovered no longer dims the rest.\n  const highlight = hovered != null && !hiddenSet.has(hovered) ? hovered : null;\n  const [announcement, setAnnouncement] = React.useState(\"\");\n  const activeIndex = active != null && active < n ? active : null;\n  const activePoint = React.useMemo(\n    () => (activeIndex == null || !anyVisible ? null : pointAt(activeIndex)),\n    [activeIndex, anyVisible, pointAt],\n  );\n\n  const onHoverRef = React.useRef(onHover);\n  React.useEffect(() => {\n    onHoverRef.current = onHover;\n  });\n  React.useEffect(() => {\n    onHoverRef.current?.(activePoint);\n  }, [activePoint]);\n\n  const nearestIndex = (px: number) => {\n    if (!n) return null;\n    const x = target.x0 + (px / W) * (target.x1 - target.x0);\n    let lo = 0;\n    let hi = n - 1;\n    while (lo < hi) {\n      const mid = (lo + hi) >> 1;\n      if (model.xs[mid] < x) lo = mid + 1;\n      else hi = mid;\n    }\n    if (lo > 0 && Math.abs(model.xs[lo - 1] - x) <= Math.abs(model.xs[lo] - x))\n      lo -= 1;\n    return lo;\n  };\n\n  const handlePointer = (event: React.PointerEvent<HTMLDivElement>) => {\n    if (!n || !anyVisible) return;\n    const rect = event.currentTarget.getBoundingClientRect();\n    const px = event.clientX - rect.left;\n    const py = event.clientY - rect.top;\n    const j = nearestIndex(Math.min(W, Math.max(0, px)));\n    setActive(j);\n    if (j == null) return;\n    // Which band sits under the pointer, so its tooltip row can stand out.\n    let band: string | null = null;\n    for (let s = seriesKeys.length - 1; s >= 0; s--) {\n      if (!visible[s]) continue;\n      const top = Y(target.y1[s][j]);\n      const bottom = Y(target.y0[s][j]);\n      if (py >= Math.min(top, bottom) - 2 && py <= Math.max(top, bottom) + 2) {\n        band = seriesKeys[s];\n        break;\n      }\n    }\n    setPointerBand(band);\n  };\n\n  const describe = (point: StackedAreaPoint) =>\n    `${point.label}: total ${valueFormatter(point.total)}. ${point.items\n      .map(\n        (item) =>\n          `${item.label} ${valueFormatter(item.value)}, ${formatShare(item.share)}`,\n      )\n      .join(\"; \")}.${point.annotations.length ? ` ${point.annotations.map((a) => a.label).join(\". \")}.` : \"\"}`;\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    if (!n || !anyVisible) return;\n    let next: number | null = null;\n    if (event.key === \"ArrowRight\")\n      next = activeIndex == null ? 0 : Math.min(n - 1, activeIndex + 1);\n    else if (event.key === \"ArrowLeft\")\n      next = activeIndex == null ? n - 1 : Math.max(0, activeIndex - 1);\n    else if (event.key === \"Home\") next = 0;\n    else if (event.key === \"End\") next = n - 1;\n    else if (event.key === \"Escape\" && activeIndex != null) {\n      event.preventDefault();\n      setActive(null);\n      return;\n    }\n    if (next == null) return;\n    event.preventDefault();\n    setPointerBand(null);\n    setActive(next);\n    setAnnouncement(describe(pointAt(next)));\n  };\n\n  const toggle = (key: string, solo: boolean) => {\n    const label = series.find((s) => s.key === key)?.label ?? key;\n    if (solo) {\n      const only =\n        seriesKeys.filter((k) => !hiddenSet.has(k)).length === 1 &&\n        !hiddenSet.has(key);\n      setHidden(only ? [] : seriesKeys.filter((k) => k !== key));\n      setAnnouncement(only ? \"Showing all series.\" : `Showing only ${label}.`);\n      return;\n    }\n    const isHidden = hiddenSet.has(key);\n    setHidden(\n      isHidden ? hidden.filter((k) => k !== key) : [...hidden, key],\n    );\n    setAnnouncement(sentence([label, isHidden ? \"shown.\" : \"hidden.\"]));\n  };\n\n  /* -------------------------------------------------------------- render */\n\n  const headerContent =\n    typeof header === \"function\" ? header(summary) : header;\n  const hasHeader =\n    title != null || description != null || actions != null || headerContent != null;\n\n  const activeX = activeIndex != null ? X(model.xs[activeIndex]) : 0;\n  const activeKeyIndex =\n    activeIndex != null\n      ? shown.keys.indexOf(model.keys[activeIndex])\n      : -1;\n\n  // Keep the tooltip inside the plot, beside the crosshair on the roomier side.\n  const tooltipRef = React.useRef<HTMLDivElement>(null);\n  const [tooltipWidth, setTooltipWidth] = React.useState(200);\n  React.useLayoutEffect(() => {\n    const el = tooltipRef.current;\n    if (el && el.offsetWidth && el.offsetWidth !== tooltipWidth)\n      setTooltipWidth(el.offsetWidth);\n  });\n  const tooltipLeft =\n    activeX + 14 + tooltipWidth <= W || activeX < W / 2\n      ? Math.min(activeX + 14, Math.max(0, W - tooltipWidth))\n      : Math.max(0, activeX - 14 - tooltipWidth);\n\n  const glide = motion\n    ? \"transition-transform duration-150 ease-out\"\n    : \"\";\n\n  const summaryText = (() => {\n    if (!n) return \"No data.\";\n    const parts = summary.series\n      .filter((s) => !s.hidden)\n      .map((s) => `${s.label} ${formatShare(s.share, 0)}`)\n      .join(\", \");\n    const range =\n      n > 1\n        ? `from ${formatX(model.xValues[0], \"tooltip\")} to ${formatX(model.xValues[n - 1], \"tooltip\")}`\n        : formatX(model.xValues[0], \"tooltip\");\n    return `${stack === \"expand\" ? \"Share\" : \"Stacked values\"} of ${summary.series.filter((s) => !s.hidden).length} series ${range}. Total ${valueFormatter(summary.total)}: ${parts}.`;\n  })();\n\n  const legend = showLegend && seriesKeys.length > 0 && (\n    <div\n      role=\"group\"\n      aria-label=\"Series\"\n      data-slot=\"stacked-area-legend\"\n      className={cn(\n        \"flex flex-wrap items-center gap-x-0.5 gap-y-0.5 px-3\",\n        legendPosition === \"bottom\" ? \"mt-3 border-t py-2\" : \"mt-3\",\n      )}\n    >\n      {meta.map((s, i) => {\n        const isHidden = hiddenSet.has(s.key);\n        const share = summary.series[i]?.share ?? 0;\n        return (\n          <button\n            key={s.key}\n            type=\"button\"\n            data-slot=\"stacked-area-legend-item\"\n            data-key={s.key}\n            data-hidden={isHidden || undefined}\n            aria-pressed={!isHidden}\n            title=\"Click to toggle. Alt-click to show only this series.\"\n            onClick={(event) => toggle(s.key, event.altKey)}\n            onKeyDown={(event) => {\n              if (event.key === \"Enter\" && event.altKey) {\n                event.preventDefault();\n                toggle(s.key, true);\n              }\n            }}\n            onPointerEnter={() => !isHidden && setHighlight(s.key)}\n            onPointerLeave={() => setHighlight(null)}\n            onFocus={() => !isHidden && setHighlight(s.key)}\n            onBlur={() => setHighlight(null)}\n            className={cn(\n              \"group/legend inline-flex h-7 max-w-full items-center gap-2 rounded-md px-2 text-xs transition-colors hover:bg-muted/70 motion-reduce:transition-none\",\n              focusRing,\n            )}\n          >\n            <span\n              aria-hidden=\"true\"\n              className=\"size-2.5 shrink-0 rounded-[3px] transition-[background,box-shadow] duration-200 motion-reduce:transition-none\"\n              style={\n                isHidden\n                  ? {\n                      boxShadow: `inset 0 0 0 1.25px color-mix(in oklab, ${s.color} 55%, transparent)`,\n                    }\n                  : {\n                      background: `linear-gradient(to bottom, color-mix(in oklab, ${s.color} 55%, transparent), color-mix(in oklab, ${s.color} 16%, transparent))`,\n                      boxShadow: `inset 0 1.5px 0 ${s.color}`,\n                    }\n              }\n            />\n            <span\n              className={cn(\n                \"truncate font-medium transition-colors motion-reduce:transition-none\",\n                isHidden ? \"text-muted-foreground/70\" : \"text-foreground\",\n              )}\n            >\n              {s.label}\n            </span>\n            {!isHidden && (\n              <span className=\"text-muted-foreground tabular-nums\">\n                {formatShare(share, 0)}\n              </span>\n            )}\n          </button>\n        );\n      })}\n      {legendPosition === \"bottom\" && seriesKeys.length > 1 && (\n        <span className=\"ml-auto hidden pr-2 text-[11px] text-muted-foreground @3xl/stacked-area:inline\">\n          Alt-click to show one\n        </span>\n      )}\n    </div>\n  );\n\n  const crosshairDots =\n    activeIndex != null && activeKeyIndex >= 0\n      ? shown.series\n          .map((key, s) => {\n            if (!visible[s] || shown.weight[s] < 0.5) return null;\n            return {\n              key,\n              color: meta[s]?.color ?? paletteColor(s),\n              y: Y(shown.y1[s][activeKeyIndex]),\n            };\n          })\n          .filter((d): d is NonNullable<typeof d> => d !== null)\n      : [];\n\n  const lowestVisible = visible.indexOf(true);\n  // Larger overlapping areas sit behind smaller ones; stacked bands draw top first.\n  const drawOrder = React.useMemo(() => {\n    const order = seriesKeys.map((_, s) => s);\n    if (stack === \"none\")\n      return order.sort(\n        (a, b) =>\n          Math.max(0, ...model.values[b]) - Math.max(0, ...model.values[a]),\n      );\n    return order.reverse();\n  }, [seriesKeys, stack, model]);\n\n  return (\n    <div\n      data-slot=\"stacked-area-chart\"\n      data-stack={stack}\n      data-curve={curve}\n      data-highlight={highlight ?? undefined}\n      className={cn(\n        \"@container/stacked-area flex min-w-0 flex-col rounded-2xl border border-border/70 bg-card text-card-foreground\",\n        \"shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.05),0_1px_2px_rgb(0_0_0/0.5)]\",\n        \"[--sac-fill-bottom:0] [--sac-fill-top:0.32] dark:[--sac-fill-top:0.36] data-[stack=stream]:[--sac-fill-bottom:0.1]\",\n        !(showLegend && legendPosition === \"bottom\") && \"pb-5\",\n        className,\n      )}\n      {...props}\n    >\n      {hasHeader && (\n        <div className=\"flex flex-col gap-4 px-5 pt-5\">\n          {(title != null || description != null || actions != null) && (\n            <div className=\"flex flex-wrap items-start gap-x-4 gap-y-3\">\n              <div className=\"min-w-[min(100%,8rem)] flex-1 space-y-1\">\n                {title != null && (\n                  <h3 className=\"truncate text-sm leading-5 font-semibold tracking-tight\">\n                    {title}\n                  </h3>\n                )}\n                {description != null && (\n                  <p\n                    id={`${id}-description`}\n                    className=\"text-[13px] leading-5 text-muted-foreground\"\n                  >\n                    {description}\n                  </p>\n                )}\n              </div>\n              {actions != null && (\n                <div className=\"flex shrink-0 flex-wrap items-center gap-2\">{actions}</div>\n              )}\n            </div>\n          )}\n          {headerContent != null && (\n            <div data-slot=\"stacked-area-header\">{headerContent}</div>\n          )}\n        </div>\n      )}\n\n      {legendPosition === \"top\" && legend}\n\n      <div className={cn(\"px-5\", hasHeader || legendPosition === \"top\" ? \"mt-4\" : \"mt-5\")}>\n        {yLabel && stack !== \"stream\" && (\n          <p\n            aria-hidden=\"true\"\n            className=\"mb-1 text-[11px] leading-4 text-muted-foreground\"\n          >\n            {yLabel}\n          </p>\n        )}\n        <div className=\"flex\">\n          {/* Value axis: an invisible copy of the labels sizes the gutter, so nothing is measured. */}\n          {stack !== \"stream\" && (\n            <div\n              aria-hidden=\"true\"\n              className=\"relative shrink-0 pr-2 text-[11px] leading-none text-muted-foreground tabular-nums\"\n              style={{ height: H }}\n            >\n              <div className=\"invisible h-0 overflow-hidden\">\n                {yTickLabels.map((label, i) => (\n                  <div key={i}>{label}</div>\n                ))}\n              </div>\n              {yTicks.map((tick, i) => (\n                <span\n                  key={`${tick}-${i}`}\n                  className={cn(\"absolute right-2 top-0 whitespace-nowrap\", glide)}\n                  style={{ transform: `translateY(calc(${r2(Y(tick))}px - 50%))` }}\n                >\n                  {yTickLabels[i]}\n                </span>\n              ))}\n            </div>\n          )}\n\n          <div className=\"min-w-0 flex-1\">\n            <div\n              ref={plotRef}\n              role=\"group\"\n              aria-roledescription=\"stacked area chart\"\n              aria-label={`${typeof title === \"string\" ? `${title}. ` : \"\"}${summaryText} Use the left and right arrow keys to read each point.`}\n              aria-describedby={description != null ? `${id}-description` : undefined}\n              tabIndex={n && anyVisible ? 0 : -1}\n              data-slot=\"stacked-area-plot\"\n              onPointerMove={handlePointer}\n              onPointerDown={handlePointer}\n              onPointerLeave={() => {\n                setActive(null);\n                setPointerBand(null);\n              }}\n              onKeyDown={onKeyDown}\n              onBlur={() => setActive(null)}\n              className={cn(\n                \"relative cursor-crosshair touch-pan-y rounded-sm select-none\",\n                \"outline-none focus-visible:ring-2 focus-visible:ring-primary/30 focus-visible:ring-offset-4 focus-visible:ring-offset-card\",\n              )}\n              style={{ height: H }}\n            >\n              {/* Gridlines */}\n              <div aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0\">\n                {yTicks.map((tick, i) => (\n                  <span\n                    key={`${tick}-${i}`}\n                    className={cn(\"absolute inset-x-0 top-0 h-px\", glide)}\n                    style={{\n                      transform: `translateY(${r2(Y(tick))}px)`,\n                      background:\n                        stack !== \"stream\" && tick === scale.lo ? baseColor : gridColor,\n                    }}\n                  />\n                ))}\n              </div>\n\n              <svg\n                aria-hidden=\"true\"\n                width=\"100%\"\n                height={H}\n                viewBox={`0 0 ${W} ${H}`}\n                preserveAspectRatio=\"none\"\n                className=\"absolute inset-0 overflow-visible\"\n              >\n                <defs>\n                  <clipPath id={`${id}-clip`}>\n                    <rect x={0} y={-6} width={W} height={H + 12} />\n                  </clipPath>\n                  {meta.map((s, i) => (\n                    <linearGradient\n                      key={s.key}\n                      id={`${id}-fill-${i}`}\n                      x1=\"0\"\n                      y1=\"0\"\n                      x2=\"0\"\n                      y2=\"1\"\n                    >\n                      <stop\n                        offset=\"0\"\n                        style={{ stopColor: s.color, stopOpacity: \"var(--sac-fill-top)\" }}\n                      />\n                      <stop\n                        offset=\"1\"\n                        style={{ stopColor: s.color, stopOpacity: \"var(--sac-fill-bottom)\" }}\n                      />\n                    </linearGradient>\n                  ))}\n                </defs>\n                <g clipPath={`url(#${id}-clip)`}>\n                  {drawOrder.map((s) => {\n                    const g = geometry[s];\n                    const m = meta[s];\n                    if (!g || !m) return null;\n                    const weight = shown.weight[s] ?? 0;\n                    const isHidden = !visible[s];\n                    const drawn = weight >= 0.002 || g.thickness >= 0.05;\n                    const dim = highlight != null && highlight !== m.key;\n                    const alpha = Math.min(1, weight * 1.5);\n                    // Bands rise from the baseline and lines draw in, bottom series first.\n                    const delay = `${s * 40}ms`;\n                    return (\n                      <g\n                        key={m.key}\n                        data-slot=\"stacked-area-series\"\n                        data-key={m.key}\n                        data-hidden={isHidden || undefined}\n                        className={cn(\n                          animate &&\n                            \"motion-safe:animate-[stacked-area-rise_760ms_cubic-bezier(0.22,1,0.36,1)_both]\",\n                        )}\n                        style={{ animationDelay: delay, transformOrigin: `0px ${r2(entranceBase)}px` }}\n                      >\n                        {drawn && (\n                          <g\n                            className=\"transition-opacity duration-150 motion-reduce:transition-none\"\n                            style={{ opacity: dim ? 0.24 : 1 }}\n                          >\n                            <path\n                              d={g.area}\n                              fill={`url(#${id}-fill-${s})`}\n                              fillOpacity={(stack === \"none\" ? 0.8 : 1) * alpha}\n                            />\n                            {stack === \"stream\" && s === lowestVisible && (\n                              <path\n                                d={g.base}\n                                fill=\"none\"\n                                stroke={m.color}\n                                strokeWidth={2}\n                                strokeLinejoin=\"round\"\n                                strokeLinecap=\"round\"\n                                strokeOpacity={alpha}\n                                pathLength={1}\n                                strokeDasharray=\"1 1\"\n                                className={cn(\n                                  \"dark:[filter:drop-shadow(0_0_6px_color-mix(in_oklab,var(--sac-line)_50%,transparent))]\",\n                                  animate &&\n                                    \"motion-safe:animate-[stacked-area-draw_820ms_cubic-bezier(0.22,1,0.36,1)_both]\",\n                                )}\n                                style={\n                                  {\n                                    \"--sac-line\": m.color,\n                                    animationDelay: delay,\n                                  } as React.CSSProperties\n                                }\n                              />\n                            )}\n                            <path\n                              d={g.line}\n                              fill=\"none\"\n                              stroke={m.color}\n                              strokeWidth={2}\n                              strokeLinejoin=\"round\"\n                              strokeLinecap=\"round\"\n                              strokeOpacity={alpha}\n                              pathLength={1}\n                              strokeDasharray=\"1 1\"\n                              className={cn(\n                                \"dark:[filter:drop-shadow(0_0_6px_color-mix(in_oklab,var(--sac-line)_50%,transparent))]\",\n                                animate &&\n                                  \"motion-safe:animate-[stacked-area-draw_820ms_cubic-bezier(0.22,1,0.36,1)_both]\",\n                              )}\n                              style={\n                                {\n                                  \"--sac-line\": m.color,\n                                  animationDelay: delay,\n                                } as React.CSSProperties\n                              }\n                            />\n                          </g>\n                        )}\n                      </g>\n                    );\n                  })}\n                </g>\n              </svg>\n\n              {/* Reference lines */}\n              {refs.map((line, i) => {\n                const color = line.color ?? \"var(--color-muted-foreground)\";\n                return (\n                  <div\n                    key={i}\n                    aria-hidden=\"true\"\n                    data-slot=\"stacked-area-reference\"\n                    className={cn(\"pointer-events-none absolute inset-x-0 top-0\", glide)}\n                    style={{ transform: `translateY(${r2(Y(line.y))}px)` }}\n                  >\n                    <div\n                      className=\"border-t border-dashed\"\n                      style={{ borderColor: `color-mix(in oklab, ${color} 70%, transparent)` }}\n                    />\n                    {line.label && (\n                      <span\n                        className=\"absolute right-0 bottom-1 rounded-sm bg-card/85 px-1 text-[10.5px] leading-4 font-medium whitespace-nowrap tabular-nums\"\n                        style={{ color }}\n                      >\n                        {line.label}\n                      </span>\n                    )}\n                  </div>\n                );\n              })}\n\n              {/* Annotations */}\n              {marks.map((m, i) => {\n                const color = m.note.color ?? \"var(--color-foreground)\";\n                const x = X(m.x);\n                const top = 4 + m.lane * 26;\n                return (\n                  <div\n                    key={i}\n                    aria-hidden=\"true\"\n                    data-slot=\"stacked-area-annotation\"\n                    data-active={m.nearest === activeIndex || undefined}\n                    className=\"pointer-events-none absolute inset-0\"\n                  >\n                    <span\n                      className=\"absolute bottom-0 w-0 border-l border-dashed\"\n                      style={{\n                        left: r2(x),\n                        top: top + 20,\n                        borderColor: `color-mix(in oklab, ${color} 38%, transparent)`,\n                      }}\n                    />\n                    <span\n                      className=\"absolute h-[7px] w-px\"\n                      style={{ left: r2(x), top: top + 14, background: `color-mix(in oklab, ${color} 38%, transparent)` }}\n                    />\n                    <span\n                      className=\"absolute flex h-5 max-w-full items-center gap-1.5 rounded-md border bg-card px-1.5 text-[11px] leading-none font-medium whitespace-nowrap text-foreground shadow-xs\"\n                      style={{\n                        top,\n                        left: r2(m.left + (x - m.fraction * W)),\n                        width: m.w,\n                      }}\n                    >\n                      <span\n                        className=\"size-1.5 shrink-0 rounded-full\"\n                        style={{ background: color }}\n                      />\n                      <span className=\"truncate\">{m.note.label}</span>\n                    </span>\n                  </div>\n                );\n              })}\n\n              {/* Crosshair */}\n              {activePoint && (\n                <div aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0\">\n                  <div\n                    className={cn(\"absolute top-0 left-0 h-full w-px\", glide)}\n                    style={{ transform: `translateX(${r2(activeX)}px)` }}\n                  >\n                    <div\n                      className=\"absolute inset-x-0 bottom-0 bg-foreground/25\"\n                      style={{ top: padTop - 4 }}\n                    />\n                  </div>\n                  {crosshairDots.map((dot) => (\n                    <span\n                      key={dot.key}\n                      className={cn(\n                        \"absolute top-0 left-0 -mt-1 -ml-1 size-2 rounded-full\",\n                        glide,\n                      )}\n                      style={{\n                        background: dot.color,\n                        boxShadow: `0 0 0 1.5px var(--color-card), 0 0 0 5px color-mix(in oklab, ${dot.color} 18%, transparent)`,\n                        transform: `translate(${r2(activeX)}px, ${r2(dot.y)}px)`,\n                      }}\n                    />\n                  ))}\n                </div>\n              )}\n\n              {/* Tooltip */}\n              {activePoint && (\n                <div\n                  ref={tooltipRef}\n                  data-slot=\"stacked-area-tooltip\"\n                  aria-hidden=\"true\"\n                  className={cn(\n                    \"pointer-events-none absolute top-0 left-0 z-10 min-w-48 rounded-xl border border-border/70 bg-popover/90 px-3 py-2.5 text-xs text-popover-foreground shadow-xl backdrop-blur-md\",\n                    glide,\n                  )}\n                  style={{\n                    transform: `translate(${r2(tooltipLeft)}px, ${padTop}px)`,\n                  }}\n                >\n                  {renderTooltip ? (\n                    renderTooltip(activePoint)\n                  ) : (\n                    <DefaultTooltip\n                      point={activePoint}\n                      format={valueFormatter}\n                      emphasis={pointerBand}\n                    />\n                  )}\n                </div>\n              )}\n\n              {!n && (\n                <p className=\"absolute inset-0 grid place-items-center text-xs text-muted-foreground\">\n                  No data to show.\n                </p>\n              )}\n              {n > 0 && !anyVisible && (\n                <div className=\"absolute inset-0 flex flex-col items-center justify-center gap-2 text-xs text-muted-foreground\">\n                  <p>Every series is hidden.</p>\n                  <button\n                    type=\"button\"\n                    onClick={() => setHidden([])}\n                    className={cn(\n                      \"h-7 rounded-md border bg-card px-2.5 font-medium text-foreground shadow-xs hover:bg-muted\",\n                      focusRing,\n                    )}\n                  >\n                    Show all\n                  </button>\n                </div>\n              )}\n            </div>\n\n            {/* Time axis */}\n            <div\n              aria-hidden=\"true\"\n              className=\"relative mt-2 h-4 text-[11px] leading-4 text-muted-foreground tabular-nums\"\n            >\n              {xTicks.map((tick, i) => {\n                const x = X(tick.x);\n                if (x < -1 || x > W + 1) return null;\n                const edgeClass =\n                  x < 28 ? \"\" : x > W - 28 ? \"-translate-x-full\" : \"-translate-x-1/2\";\n                return (\n                  <span\n                    key={`${tick.x}-${i}`}\n                    className={cn(\"absolute top-0 whitespace-nowrap\", edgeClass)}\n                    style={{ left: r2(x) }}\n                  >\n                    {tick.label}\n                  </span>\n                );\n              })}\n            </div>\n          </div>\n        </div>\n      </div>\n\n      {legendPosition === \"bottom\" && legend}\n\n      <div className=\"sr-only\">\n        <table>\n          <caption>{summaryText}</caption>\n          <thead>\n            <tr>\n              <th scope=\"col\">{index}</th>\n              {meta.map((s) => (\n                <th key={s.key} scope=\"col\">\n                  {s.label}\n                </th>\n              ))}\n              <th scope=\"col\">Total</th>\n            </tr>\n          </thead>\n          <tbody>\n            {model.rows.map((_, j) => (\n              <tr key={model.keys[j]}>\n                <th scope=\"row\">{formatX(model.xValues[j], \"tooltip\")}</th>\n                {meta.map((s, si) => (\n                  <td key={s.key}>{valueFormatter(model.values[si][j])}</td>\n                ))}\n                <td>\n                  {valueFormatter(\n                    model.values.reduce((sum, values) => sum + values[j], 0),\n                  )}\n                </td>\n              </tr>\n            ))}\n          </tbody>\n        </table>\n      </div>\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {announcement}\n      </p>\n\n      <style href=\"overtrue-stacked-area-chart\" precedence=\"default\">\n        {`@keyframes stacked-area-rise{from{transform:scaleY(0)}to{transform:scaleY(1)}}@keyframes stacked-area-draw{from{stroke-dashoffset:1}to{stroke-dashoffset:0}}`}\n      </style>\n    </div>\n  );\n}\n\nfunction DefaultTooltip({\n  point,\n  format,\n  emphasis,\n}: {\n  point: StackedAreaPoint;\n  format: (value: number) => string;\n  emphasis: string | null;\n}) {\n  return (\n    <div className=\"grid grid-cols-[auto_minmax(0,1fr)_auto_auto] items-center gap-x-2 gap-y-1\">\n      <p className=\"col-span-4 mb-1 font-medium text-foreground\">{point.label}</p>\n      {point.items.map((item) => (\n        <React.Fragment key={item.key}>\n          <span\n            aria-hidden=\"true\"\n            className=\"h-2.5 w-[3px] rounded-full\"\n            style={{ background: item.color }}\n          />\n          <span\n            className={cn(\n              \"truncate\",\n              emphasis === item.key ? \"font-medium text-foreground\" : \"text-muted-foreground\",\n            )}\n          >\n            {item.label}\n          </span>\n          <span\n            className={cn(\n              \"pl-3 text-right tabular-nums\",\n              emphasis === item.key ? \"font-semibold\" : \"font-medium\",\n            )}\n          >\n            {format(item.value)}\n          </span>\n          <span className=\"w-11 text-right text-[11px] text-muted-foreground tabular-nums\">\n            {formatShare(item.share)}\n          </span>\n        </React.Fragment>\n      ))}\n      <span className=\"col-span-4 my-0.5 h-px bg-border\" />\n      <span />\n      <span className=\"text-muted-foreground\">Total</span>\n      <span className=\"pl-3 text-right font-semibold tabular-nums\">\n        {format(point.total)}\n      </span>\n      <span />\n      {point.annotations.map((note, i) => (\n        <p\n          key={i}\n          className=\"col-span-4 mt-1 flex items-center gap-1.5 border-t border-dashed pt-1.5 text-[11px] text-muted-foreground\"\n        >\n          <span\n            aria-hidden=\"true\"\n            className=\"size-1.5 shrink-0 rounded-full\"\n            style={{ background: note.color ?? \"var(--color-foreground)\" }}\n          />\n          {note.label}\n        </p>\n      ))}\n    </div>\n  );\n}\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/components/stacked-area-chart. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
