{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "pipeline-chart",
  "title": "Pipeline chart",
  "description": "A chart card that plots several pipeline stages (contacted, replied, converted) over time on real axes, with a per-stage legend that doubles as the summary, a line/bar toggle, a crosshair tooltip and a period dropdown that opens a custom-range calendar.",
  "dependencies": [
    "motion",
    "lucide-react"
  ],
  "registryDependencies": [
    "https://bash-ui-registry.vercel.app/r/date-range-calendar.json"
  ],
  "files": [
    {
      "path": "registry/items/pipeline-chart/pipeline-chart.tsx",
      "content": "\"use client\";\n\nimport { useCallback, useId, useMemo, useState } from \"react\";\nimport { Activity, BarChart3 } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotionConfig } from \"motion/react\";\n\nimport { cn } from \"@/lib/utils\";\nimport {\n  DateRangePicker,\n  type PeriodOption,\n} from \"@/components/date-range-picker\";\n\nexport type { PeriodOption };\n\n/**\n * A time-series chart card for a pipeline: several named stages (contacted,\n * replied, converted) against a real pair of axes, counts up the left and dates\n * along the bottom. The plot is the content and spans the card; each stage's\n * figure sits above it with its own change against the window before, because\n * three lines deserve three captions.\n *\n * The window is the reader's: presets of trailing days, or a custom range on a\n * calendar bounded to the data. Long windows are bucketed into weeks (or\n * four-week blocks) so three lines stay legible. Changing the window morphs the\n * curves rather than cutting between them; the line/bar toggle, legend\n * show/hide and a crosshair tooltip (pointer or arrow keys) round it out.\n *\n * Colours are fixed per series index, never per visible position, so hiding a\n * series never repaints the ones that remain.\n */\n\n/** One day's count. `date` is a UTC ISO day, YYYY-MM-DD. */\nexport type SeriesPoint = { date: string; value: number };\n\n/** A named stage. `color` overrides the default colour for its index. */\nexport type PipelineSeries = { name: string; data: SeriesPoint[]; color?: string };\n\nexport type ChartView = \"curve\" | \"bars\";\n\n/** A legend figure supplied by the caller instead of the summed window. */\nexport type SeriesTotal = { total: number; previous?: number | null };\n\n/**\n * Categorical series colours, in fixed assignment order: green, blue, amber,\n * red, grey. Past three, identity leans on the legend and end-of-line labels.\n */\nexport const PIPELINE_SERIES_COLORS = [\n  \"var(--go)\",\n  \"var(--lead)\",\n  \"var(--hold)\",\n  \"var(--stop)\",\n  \"var(--dim)\",\n];\n\nconst EASE = [0.2, 0.7, 0.2, 1] as const;\n\n/** How many buckets before daily points stop being readable as three lines. */\nconst MAX_DAILY_BUCKETS = 35;\nconst MAX_WEEKLY_BUCKETS = 220;\n\ntype Grain = \"day\" | \"week\" | \"month\";\n\nconst GRAIN_NOTE: Record<Grain, string> = {\n  day: \"daily totals\",\n  week: \"weekly totals\",\n  month: \"four-week totals\",\n};\n\nconst GRAIN_DAYS: Record<Grain, number> = { day: 1, week: 7, month: 28 };\n\n/** A plotted point: a span of days and what happened across it. */\ntype Bucket = { start: string; end: string; value: number };\n\n/** Top leaves room for the axis unit above the highest gridline. */\nconst PLOT_PAD = { top: 28, bottom: 30, left: 46 } as const;\n/** Room at the right for the end-of-line labels; dropped on narrow cards. */\nconst END_LABEL_W = 78;\nconst END_LABEL_MIN_WIDTH = 520;\n/** Minimum vertical gap between two end labels before they are pushed apart. */\nconst END_LABEL_LEAD = 13;\nconst BAR_MAX_W = 24;\n/** Every curve is sampled to the same number of Bézier segments so it can morph. */\nconst SPLINE_SAMPLES = 40;\n\nconst SHORT_MONTHS = [\n  \"Jan\",\n  \"Feb\",\n  \"Mar\",\n  \"Apr\",\n  \"May\",\n  \"Jun\",\n  \"Jul\",\n  \"Aug\",\n  \"Sep\",\n  \"Oct\",\n  \"Nov\",\n  \"Dec\",\n] as const;\n\n// Month names spelled here, not by Intl: runtimes disagree on \"Sep\".\nfunction monthDay(d: Date): string {\n  return `${d.getUTCDate()} ${SHORT_MONTHS[d.getUTCMonth()]}`;\n}\nfunction monthDayYear(d: Date): string {\n  return `${monthDay(d)} ${d.getUTCFullYear()}`;\n}\nfunction parseDay(iso: string): Date {\n  return new Date(`${iso}T00:00:00Z`);\n}\n\nfunction grainFor(buckets: number): Grain {\n  if (buckets <= MAX_DAILY_BUCKETS) return \"day\";\n  if (buckets <= MAX_WEEKLY_BUCKETS) return \"week\";\n  return \"month\";\n}\n\n/**\n * Trim a series to the window. A preset keeps the trailing N points; an\n * explicit from/to filters inclusively and wins over the preset.\n */\nfunction sliceWindow(points: SeriesPoint[], option: PeriodOption): SeriesPoint[] {\n  const { points: n, from, to } = option;\n  let out = points;\n  if (from) out = out.filter((point) => point.date >= from);\n  if (to) out = out.filter((point) => point.date <= to);\n  if (!from && !to && n && n < out.length) out = out.slice(-n);\n  return out;\n}\n\n/**\n * Sum daily points into buckets, counted back from the most recent day, so\n * every bucket covers the same number of whole days and the last one is\n * comparable to the one before it. A part-finished calendar week would always\n * plot as a cliff. The oldest few days fall off the left edge instead.\n */\nfunction bucketSeries(points: SeriesPoint[], grain: Grain): Bucket[] {\n  const size = GRAIN_DAYS[grain];\n  if (size === 1) {\n    return points.map((point) => ({ start: point.date, end: point.date, value: point.value }));\n  }\n  const buckets: Bucket[] = [];\n  for (let end = points.length; end - size >= 0; end -= size) {\n    const chunk = points.slice(end - size, end);\n    buckets.unshift({\n      start: chunk[0].date,\n      end: chunk[chunk.length - 1].date,\n      value: chunk.reduce((sum, point) => sum + point.value, 0),\n    });\n  }\n  return buckets;\n}\n\n/** Axis ticks on round numbers, from zero, never fractional for counts. */\nfunction axisTicks(max: number, target = 4): number[] {\n  if (!Number.isFinite(max) || max <= 0) return [0, 1];\n  const raw = max / target;\n  const magnitude = 10 ** Math.floor(Math.log10(raw));\n  const normalised = raw / magnitude;\n  // 1.5 and 3 are on the ladder so a max of 600 tops out at 600, not 800.\n  const rungs = [1, 1.5, 2, 2.5, 3, 5, 10];\n  const step = Math.max(1, (rungs.find((rung) => normalised <= rung) ?? 10) * magnitude);\n  const top = Math.ceil(max / step) * step;\n  const ticks: number[] = [];\n  for (let value = 0; value <= top + 1e-9; value += step) ticks.push(Math.round(value));\n  return ticks;\n}\n\n/**\n * A monotone (Fritsch–Carlson) spline through the points, resampled to a fixed\n * number of Bézier segments. Fixed topology is the point: every path has the\n * same command structure, so Motion can morph one window's curve into the next.\n */\nfunction splinePath(points: { x: number; y: number }[], samples = SPLINE_SAMPLES): string {\n  const n = points.length;\n  if (n === 0) return \"\";\n  if (n === 1) {\n    const { x, y } = points[0];\n    return `M ${x.toFixed(2)} ${y.toFixed(2)} L ${x.toFixed(2)} ${y.toFixed(2)}`;\n  }\n\n  const dxs: number[] = [];\n  const slopes: number[] = [];\n  for (let i = 0; i < n - 1; i++) {\n    const dx = points[i + 1].x - points[i].x;\n    dxs.push(dx);\n    slopes.push(dx === 0 ? 0 : (points[i + 1].y - points[i].y) / dx);\n  }\n\n  const tangents: number[] = new Array(n);\n  tangents[0] = slopes[0];\n  tangents[n - 1] = slopes[n - 2];\n  for (let i = 1; i < n - 1; i++) {\n    const prev = slopes[i - 1];\n    const next = slopes[i];\n    if (prev * next <= 0) {\n      tangents[i] = 0;\n    } else {\n      const hPrev = dxs[i - 1];\n      const hNext = dxs[i];\n      tangents[i] = (3 * (hPrev + hNext)) / ((2 * hNext + hPrev) / prev + (hNext + 2 * hPrev) / next);\n    }\n  }\n  for (let i = 0; i < n - 1; i++) {\n    if (slopes[i] === 0) {\n      tangents[i] = 0;\n      tangents[i + 1] = 0;\n      continue;\n    }\n    const alpha = tangents[i] / slopes[i];\n    const beta = tangents[i + 1] / slopes[i];\n    const distance = alpha * alpha + beta * beta;\n    if (distance > 9) {\n      const tau = 3 / Math.sqrt(distance);\n      tangents[i] = tau * alpha * slopes[i];\n      tangents[i + 1] = tau * beta * slopes[i];\n    }\n  }\n\n  const evaluate = (x: number): { y: number; dy: number } => {\n    if (x <= points[0].x) return { y: points[0].y, dy: tangents[0] };\n    if (x >= points[n - 1].x) return { y: points[n - 1].y, dy: tangents[n - 1] };\n    let i = 0;\n    while (i < n - 2 && points[i + 1].x < x) i++;\n    const h = points[i + 1].x - points[i].x;\n    if (h === 0) return { y: points[i].y, dy: 0 };\n    const t = (x - points[i].x) / h;\n    const t2 = t * t;\n    const t3 = t2 * t;\n    const y0 = points[i].y;\n    const y1 = points[i + 1].y;\n    const m0 = tangents[i];\n    const m1 = tangents[i + 1];\n    return {\n      y:\n        (2 * t3 - 3 * t2 + 1) * y0 +\n        (t3 - 2 * t2 + t) * h * m0 +\n        (-2 * t3 + 3 * t2) * y1 +\n        (t3 - t2) * h * m1,\n      dy:\n        ((6 * t2 - 6 * t) * y0 +\n          (3 * t2 - 4 * t + 1) * h * m0 +\n          (-6 * t2 + 6 * t) * y1 +\n          (3 * t2 - 2 * t) * h * m1) /\n        h,\n    };\n  };\n\n  const minX = points[0].x;\n  const maxX = points[n - 1].x;\n  const step = (maxX - minX) / (samples - 1);\n  const taken = Array.from({ length: samples }, (_, k) => {\n    const x = minX + k * step;\n    const { y, dy } = evaluate(x);\n    return { x, y, dy };\n  });\n\n  let path = `M ${taken[0].x.toFixed(2)} ${taken[0].y.toFixed(2)}`;\n  for (let k = 0; k < samples - 1; k++) {\n    const a = taken[k];\n    const b = taken[k + 1];\n    const dx = b.x - a.x;\n    path += ` C ${(a.x + dx / 3).toFixed(2)} ${(a.y + (a.dy * dx) / 3).toFixed(2)}, ${(\n      b.x -\n      dx / 3\n    ).toFixed(2)} ${(b.y - (b.dy * dx) / 3).toFixed(2)}, ${b.x.toFixed(2)} ${b.y.toFixed(2)}`;\n  }\n  return path;\n}\n\n/** A column with a rounded cap and square feet on the baseline. */\nfunction columnPath(x: number, y: number, width: number, baseline: number): string {\n  const height = Math.max(baseline - y, 0);\n  const radius = Math.min(4, width / 2, height);\n  if (height <= 0.5) return `M ${x} ${baseline} L ${x + width} ${baseline}`;\n  return [\n    `M ${x.toFixed(2)} ${baseline.toFixed(2)}`,\n    `L ${x.toFixed(2)} ${(y + radius).toFixed(2)}`,\n    `Q ${x.toFixed(2)} ${y.toFixed(2)} ${(x + radius).toFixed(2)} ${y.toFixed(2)}`,\n    `L ${(x + width - radius).toFixed(2)} ${y.toFixed(2)}`,\n    `Q ${(x + width).toFixed(2)} ${y.toFixed(2)} ${(x + width).toFixed(2)} ${(y + radius).toFixed(2)}`,\n    `L ${(x + width).toFixed(2)} ${baseline.toFixed(2)}`,\n    \"Z\",\n  ].join(\" \");\n}\n\nfunction formatCount(value: number): string {\n  return value.toLocaleString(\"en-GB\");\n}\n\nfunction formatCompactCount(value: number): string {\n  if (Math.abs(value) >= 1_000_000) return `${(value / 1_000_000).toFixed(1).replace(/\\.0$/, \"\")}M`;\n  if (Math.abs(value) >= 10_000) return `${Math.round(value / 1000)}K`;\n  return formatCount(value);\n}\n\n/** The x-axis tick under a bucket: the day it ends. */\nfunction formatAxisDate(bucket: Bucket, withYear: boolean): string {\n  return (withYear ? monthDayYear : monthDay)(parseDay(bucket.end));\n}\n\n/** The span a bucket covers, spelled out for the tooltip and the table. */\nfunction formatBucketRange(bucket: Bucket): string {\n  if (bucket.start === bucket.end) return monthDayYear(parseDay(bucket.end));\n  return `${monthDay(parseDay(bucket.start))} – ${monthDayYear(parseDay(bucket.end))}`;\n}\n\n/**\n * Change against the window immediately before this one. null where there is no\n * window before it: a made-up \"+100%\" against nothing is worse than nothing.\n */\nfunction changeFor(\n  total: number,\n  previous: number | null,\n): { text: string; direction: 1 | 0 | -1 } | null {\n  if (previous === null) return null;\n  if (previous === 0) {\n    if (total === 0) return { text: \"no change\", direction: 0 };\n    return { text: \"all new\", direction: 1 };\n  }\n  const pct = ((total - previous) / previous) * 100;\n  if (Math.abs(pct) < 0.5) return { text: \"no change\", direction: 0 };\n  return {\n    text: `${pct > 0 ? \"+\" : \"−\"}${Math.abs(pct).toFixed(0)}%`,\n    direction: pct > 0 ? 1 : -1,\n  };\n}\n\n/** Line or bars, with a pill that slides between the two. */\nfunction ViewToggle({\n  value,\n  onChange,\n  layoutId,\n}: {\n  value: ChartView;\n  onChange: (view: ChartView) => void;\n  layoutId: string;\n}) {\n  const reduceMotion = useReducedMotionConfig();\n  const item = (view: ChartView, Icon: typeof Activity, label: string) => {\n    const isSelected = value === view;\n    return (\n      <button\n        type=\"button\"\n        aria-label={label}\n        aria-pressed={isSelected}\n        onClick={() => onChange(view)}\n        className={cn(\n          \"relative z-10 rounded-full p-1.5 transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-lead\",\n          isSelected ? \"font-semibold text-ink\" : \"text-faint hover:text-ink\",\n        )}\n      >\n        {isSelected && (\n          <motion.div\n            layoutId={layoutId}\n            className=\"absolute inset-0 rounded-full bg-card shadow-sm\"\n            transition={\n              reduceMotion ? { duration: 0 } : { type: \"spring\", stiffness: 450, damping: 30 }\n            }\n          />\n        )}\n        <span className=\"relative z-10 block\">\n          <Icon size={14} strokeWidth={2.5} />\n        </span>\n      </button>\n    );\n  };\n\n  return (\n    <div className=\"flex items-center gap-0.5 rounded-full bg-paper p-0.5\">\n      {item(\"curve\", Activity, \"Line view\")}\n      {item(\"bars\", BarChart3, \"Bar view\")}\n    </div>\n  );\n}\n\nexport interface PipelineChartProps {\n  title: string;\n  /** What one point means, in the words of the job. The grain is appended. */\n  subtitle?: string;\n  /** One series per stage, daily points in date order, all the same dates. */\n  series: PipelineSeries[];\n  /** Plural noun for the y-axis caption, e.g. \"clients\". */\n  unit?: string;\n  /** Label of the preset to open on. */\n  period?: string;\n  periodOptions?: PeriodOption[];\n  /** Adds a \"Custom range\" step with a calendar bounded to the data. */\n  allowCustomRange?: boolean;\n  /**\n   * Fires when the reader picks a window: the option, and the first and last\n   * day it resolved to in the data (null when the window holds nothing). Use it\n   * to fetch a fresh window; the card already filters what it was given.\n   */\n  onRangeChange?: (option: PeriodOption, window: { from: string; to: string } | null) => void;\n  /**\n   * Legend figures per series, overriding the summed window (e.g. distinct\n   * clients counted by the server). `previous` enables the change figure.\n   */\n  totals?: (SeriesTotal | undefined)[];\n  defaultView?: ChartView;\n  /** Unique across the page: the view toggle's pill animates between matches. */\n  toggleId?: string;\n  emptyMessage?: string;\n  /** Fixes \"today\" for the calendar's presets; defaults to the clock. */\n  now?: Date;\n  className?: string;\n}\n\nexport function PipelineChart({\n  title,\n  subtitle,\n  series,\n  unit = \"\",\n  period = \"Past 30 days\",\n  periodOptions,\n  allowCustomRange = false,\n  onRangeChange,\n  totals: totalsOverride,\n  defaultView = \"curve\",\n  toggleId,\n  emptyMessage = \"Nothing to chart yet. This fills in as outreach happens.\",\n  now,\n  className,\n}: PipelineChartProps) {\n  const reduceMotion = useReducedMotionConfig();\n  const reactId = useId().replace(/:/g, \"\");\n  const periods = useMemo<PeriodOption[]>(\n    () =>\n      periodOptions ?? [\n        { label: \"Past 30 days\", points: 30 },\n        { label: \"Past 90 days\", points: 90 },\n      ],\n    [periodOptions],\n  );\n  const defaultPeriod = periods.find((option) => option.label === period) ?? periods[0];\n\n  const [selected, setSelected] = useState<PeriodOption>(() => defaultPeriod);\n  const [view, setView] = useState<ChartView>(defaultView);\n  const [hiddenNames, setHiddenNames] = useState<string[]>([]);\n  const [active, setActive] = useState<number | null>(null);\n  const [size, setSize] = useState({ width: 0, height: 0 });\n\n  const measure = useCallback((node: HTMLDivElement | null) => {\n    if (!node) return;\n    const observer = new ResizeObserver(([entry]) => {\n      const box = entry.contentRect;\n      setSize({ width: box.width, height: box.height });\n    });\n    observer.observe(node);\n    setSize({ width: node.clientWidth, height: node.clientHeight });\n    return () => observer.disconnect();\n  }, []);\n\n  /** The full extent of the data, for the calendar's selectable bounds. */\n  const bounds = useMemo(() => {\n    let min: string | null = null;\n    let max: string | null = null;\n    for (const entry of series) {\n      for (const point of entry.data) {\n        if (min === null || point.date < min) min = point.date;\n        if (max === null || point.date > max) max = point.date;\n      }\n    }\n    return { min, max };\n  }, [series]);\n\n  const choosePeriod = (option: PeriodOption) => {\n    setSelected(option);\n    setActive(null);\n    if (onRangeChange) {\n      const slice = sliceWindow(series[0]?.data ?? [], option);\n      onRangeChange(\n        option,\n        slice.length ? { from: slice[0].date, to: slice[slice.length - 1].date } : null,\n      );\n    }\n  };\n\n  const windowed = useMemo(\n    () => series.map((entry) => ({ ...entry, data: sliceWindow(entry.data, selected) })),\n    [series, selected],\n  );\n\n  /** The same length of time immediately before the window, for the change figures. */\n  const previousWindow = useMemo(() => {\n    const length = windowed[0]?.data.length ?? 0;\n    if (length === 0) return series.map(() => [] as SeriesPoint[]);\n    const firstDate = windowed[0].data[0].date;\n    return series.map((entry) =>\n      entry.data.filter((point) => point.date < firstDate).slice(-length),\n    );\n  }, [series, windowed]);\n\n  const grain = grainFor(windowed[0]?.data.length ?? 0);\n\n  const bucketed = useMemo(\n    () => windowed.map((entry) => ({ ...entry, data: bucketSeries(entry.data, grain) })),\n    [windowed, grain],\n  );\n\n  const totals = useMemo(\n    () =>\n      windowed.map((entry, index) => {\n        const override = totalsOverride?.[index];\n        if (override) {\n          return {\n            total: override.total,\n            change: changeFor(override.total, override.previous ?? null),\n          };\n        }\n        const total = entry.data.reduce((sum, point) => sum + point.value, 0);\n        const before = previousWindow[index];\n        const previous =\n          before.length === 0 ? null : before.reduce((sum, point) => sum + point.value, 0);\n        return { total, change: changeFor(total, previous) };\n      }),\n    [windowed, previousWindow, totalsOverride],\n  );\n\n  const visible = bucketed.filter((entry) => !hiddenNames.includes(entry.name));\n  const length = bucketed[0]?.data.length ?? 0;\n  const hasData = length >= 2;\n\n  const colourOf = useCallback(\n    (name: string) => {\n      const index = series.findIndex((entry) => entry.name === name);\n      const own = index >= 0 ? series[index].color : undefined;\n      return own ?? PIPELINE_SERIES_COLORS[(index < 0 ? 0 : index) % PIPELINE_SERIES_COLORS.length];\n    },\n    [series],\n  );\n\n  const spansYears = useMemo(() => {\n    const first = bucketed[0]?.data[0]?.end;\n    const last = bucketed[0]?.data[length - 1]?.end;\n    return Boolean(first && last && first.slice(0, 4) !== last.slice(0, 4));\n  }, [bucketed, length]);\n\n  const showEndLabels = size.width >= END_LABEL_MIN_WIDTH;\n  const padRight = showEndLabels ? END_LABEL_W : 14;\n  const plotLeft = PLOT_PAD.left;\n  const plotTop = PLOT_PAD.top;\n  const plotWidth = Math.max(size.width - plotLeft - padRight, 1);\n  const plotBottom = Math.max(size.height - PLOT_PAD.bottom, plotTop + 1);\n  const plotHeight = plotBottom - plotTop;\n\n  const yMaxRaw = useMemo(() => {\n    let max = 0;\n    for (const entry of visible) for (const point of entry.data) max = Math.max(max, point.value);\n    return max;\n  }, [visible]);\n\n  const ticks = useMemo(() => axisTicks(yMaxRaw), [yMaxRaw]);\n  const yMax = ticks[ticks.length - 1] || 1;\n\n  /**\n   * Columns are centred in a slot so the first group cannot straddle the axis;\n   * a line still starts on the axis and ends on the right edge.\n   */\n  const toX = useCallback(\n    (index: number) => {\n      if (length <= 1) return plotLeft + plotWidth / 2;\n      if (view === \"bars\") return plotLeft + (plotWidth / length) * (index + 0.5);\n      return plotLeft + (index / (length - 1)) * plotWidth;\n    },\n    [length, plotLeft, plotWidth, view],\n  );\n  const toY = useCallback(\n    (value: number) => plotBottom - (value / yMax) * plotHeight,\n    [plotBottom, plotHeight, yMax],\n  );\n\n  const xTicks = useMemo(() => {\n    if (!hasData || plotWidth <= 0) return [];\n    const room = grain === \"day\" ? 74 : 86;\n    const count = Math.max(2, Math.min(6, Math.floor(plotWidth / room)));\n    const indices = new Set<number>();\n    for (let i = 0; i < count; i++) indices.add(Math.round((i * (length - 1)) / (count - 1)));\n    return [...indices].sort((a, b) => a - b);\n  }, [hasData, plotWidth, grain, length]);\n\n  /**\n   * End-of-line labels, pushed apart where two lines finish close together;\n   * each one that moved gets a leader line back to its point.\n   */\n  const endLabels = useMemo(() => {\n    if (!showEndLabels || !hasData) return [];\n    const raw = visible\n      .map((entry) => {\n        const point = entry.data[entry.data.length - 1];\n        if (!point) return null;\n        return { name: entry.name, y: toY(point.value), anchor: toY(point.value) };\n      })\n      .filter((item): item is { name: string; y: number; anchor: number } => item !== null)\n      .sort((a, b) => a.y - b.y);\n    for (let i = 1; i < raw.length; i++) {\n      if (raw[i].y - raw[i - 1].y < END_LABEL_LEAD) raw[i].y = raw[i - 1].y + END_LABEL_LEAD;\n    }\n    const overflow = raw.length ? raw[raw.length - 1].y - plotBottom : 0;\n    if (overflow > 0) for (const item of raw) item.y -= overflow;\n    return raw;\n  }, [showEndLabels, hasData, visible, toY, plotBottom]);\n\n  const handlePointer = (event: React.PointerEvent<HTMLDivElement>) => {\n    if (length <= 1) return setActive(0);\n    const box = event.currentTarget.getBoundingClientRect();\n    const ratio = (event.clientX - box.left - plotLeft) / plotWidth;\n    const index = view === \"bars\" ? Math.floor(ratio * length) : Math.round(ratio * (length - 1));\n    setActive(Math.min(length - 1, Math.max(0, index)));\n  };\n\n  const handleKey = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    if (event.key !== \"ArrowLeft\" && event.key !== \"ArrowRight\") return;\n    event.preventDefault();\n    const step = event.key === \"ArrowRight\" ? 1 : -1;\n    setActive((current) => {\n      const next = (current ?? (step > 0 ? -1 : length)) + step;\n      return Math.min(length - 1, Math.max(0, next));\n    });\n  };\n\n  const activeIndex = active === null ? null : Math.min(active, Math.max(length - 1, 0));\n  const activeBucket = activeIndex === null ? null : (bucketed[0]?.data[activeIndex] ?? null);\n  const grainNote = GRAIN_NOTE[grain];\n\n  const spring = (stiffness: number, damping: number) =>\n    reduceMotion ? { duration: 0 } : ({ type: \"spring\", stiffness, damping } as const);\n\n  return (\n    <div\n      className={cn(\n        \"flex w-full flex-col rounded-panel border border-rule bg-card p-4 font-body shadow-[0_2px_10px_color-mix(in_oklab,var(--ink)_4%,transparent)] sm:p-6\",\n        className,\n      )}\n    >\n      {/* Header: what this is, then how much of it to show. */}\n      <div className=\"flex flex-wrap items-start justify-between gap-x-4 gap-y-2\">\n        <div className=\"flex min-w-0 items-center gap-3\">\n          <div className=\"min-w-0\">\n            <h3 className=\"font-heading text-[20px] font-semibold tracking-tight text-ink\">\n              {title}\n            </h3>\n            <p className=\"mt-0.5 text-[12px] text-dim\">\n              {subtitle ? `${subtitle} · ${grainNote}` : grainNote}\n            </p>\n          </div>\n          <ViewToggle\n            value={view}\n            onChange={setView}\n            layoutId={toggleId ?? `${reactId}-view-toggle`}\n          />\n        </div>\n        <DateRangePicker\n          value={selected.label}\n          options={periods}\n          onChange={choosePeriod}\n          allowCustomRange={allowCustomRange}\n          defaultOption={defaultPeriod}\n          rangeMin={bounds.min}\n          rangeMax={bounds.max}\n          now={now}\n        />\n      </div>\n\n      {/* The legend is also the summary: one figure per series, with its change. */}\n      <div className=\"mt-4 flex flex-wrap gap-x-6 gap-y-3\">\n        {bucketed.map((entry, index) => {\n          const isHidden = hiddenNames.includes(entry.name);\n          const summary = totals[index];\n          return (\n            <button\n              key={entry.name}\n              type=\"button\"\n              aria-pressed={!isHidden}\n              onClick={() =>\n                setHiddenNames((current) => {\n                  if (!current.includes(entry.name)) {\n                    // Never let the reader hide the last line and get an empty frame.\n                    return current.length >= bucketed.length - 1\n                      ? current\n                      : [...current, entry.name];\n                  }\n                  return current.filter((name) => name !== entry.name);\n                })\n              }\n              className={cn(\n                \"group flex items-start gap-2 rounded-xl px-1.5 py-1 text-left transition-opacity focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-lead\",\n                isHidden ? \"opacity-40\" : \"opacity-100\",\n              )}\n              title={\n                isHidden ? `Show ${entry.name.toLowerCase()}` : `Hide ${entry.name.toLowerCase()}`\n              }\n            >\n              <span\n                aria-hidden\n                className=\"mt-[7px] h-[3px] w-4 shrink-0 rounded-full\"\n                style={{ background: colourOf(entry.name) }}\n              />\n              <span className=\"flex flex-col\">\n                <span className=\"text-[12px] font-medium text-dim\">{entry.name}</span>\n                <span className=\"flex items-baseline gap-1.5\">\n                  <AnimatePresence mode=\"popLayout\" initial={false}>\n                    <motion.span\n                      key={`${entry.name}-${summary.total}`}\n                      initial={reduceMotion ? { opacity: 0 } : { opacity: 0, y: 5 }}\n                      animate={{ opacity: 1, y: 0 }}\n                      exit={reduceMotion ? { opacity: 0 } : { opacity: 0, y: -5 }}\n                      transition={{ duration: 0.22 }}\n                      className=\"text-[24px] font-semibold leading-tight tracking-tight tabular-nums text-ink\"\n                    >\n                      {formatCount(summary.total)}\n                    </motion.span>\n                  </AnimatePresence>\n                  {summary.change && (\n                    <span\n                      className={cn(\n                        \"text-[11px] font-semibold\",\n                        summary.change.direction > 0\n                          ? \"text-go\"\n                          : summary.change.direction < 0\n                            ? \"text-stop\"\n                            : \"text-dim\",\n                      )}\n                      title=\"Against the same length of time just before this window\"\n                    >\n                      {summary.change.text}\n                    </span>\n                  )}\n                </span>\n              </span>\n            </button>\n          );\n        })}\n      </div>\n\n      {!hasData ? (\n        <div className=\"flex min-h-[200px] flex-1 items-center justify-center\">\n          <p className=\"max-w-xs text-center text-sm text-dim\">{emptyMessage}</p>\n        </div>\n      ) : (\n        <>\n          <div\n            ref={measure}\n            role=\"img\"\n            tabIndex={0}\n            aria-label={`${title}. ${bucketed\n              .map((entry, index) => `${entry.name}: ${formatCount(totals[index].total)}`)\n              .join(\", \")} over ${selected.label.toLowerCase()}. Use the left and right arrow keys to read each point.`}\n            aria-describedby={`${reactId}-table`}\n            className=\"relative mt-3 min-h-[220px] w-full flex-1 touch-none select-none rounded-lg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-lead\"\n            onPointerMove={handlePointer}\n            onPointerDown={handlePointer}\n            onPointerLeave={() => setActive(null)}\n            onKeyDown={handleKey}\n            onBlur={() => setActive(null)}\n          >\n            {size.width > 0 && (\n              <svg\n                width={size.width}\n                height={size.height}\n                className=\"absolute inset-0 overflow-visible\"\n              >\n                {/* Gridlines: solid hairlines, one step off the surface. */}\n                {ticks.map((tick) => (\n                  <line\n                    key={`grid-${tick}`}\n                    x1={plotLeft}\n                    x2={plotLeft + plotWidth}\n                    y1={toY(tick)}\n                    y2={toY(tick)}\n                    stroke=\"currentColor\"\n                    strokeWidth={1}\n                    className={tick === 0 ? \"text-ink/[0.14]\" : \"text-ink/[0.06]\"}\n                  />\n                ))}\n\n                {/* The unit, kept attached to the axis it belongs to. */}\n                {unit && (\n                  <text\n                    x={plotLeft - 10}\n                    y={plotTop - 12}\n                    textAnchor=\"end\"\n                    className=\"fill-foreground/35 text-[10px]\"\n                  >\n                    {unit}\n                  </text>\n                )}\n\n                {/* Y-axis labels, on the left where a reader looks for them. */}\n                {ticks.map((tick) => (\n                  <text\n                    key={`ytick-${tick}`}\n                    x={plotLeft - 10}\n                    y={toY(tick)}\n                    textAnchor=\"end\"\n                    dominantBaseline=\"middle\"\n                    className=\"fill-foreground/45 text-[11px] tabular-nums\"\n                  >\n                    {formatCompactCount(tick)}\n                  </text>\n                ))}\n\n                {/* X-axis labels along the bottom. */}\n                {xTicks.map((index, position) => (\n                  <text\n                    key={`xtick-${index}`}\n                    x={toX(index)}\n                    y={plotBottom + 18}\n                    textAnchor={\n                      position === 0 ? \"start\" : position === xTicks.length - 1 ? \"end\" : \"middle\"\n                    }\n                    className=\"fill-foreground/45 text-[11px]\"\n                  >\n                    {formatAxisDate(bucketed[0].data[index], spansYears)}\n                  </text>\n                ))}\n\n                {/* Crosshair: readers aim at a date, not at a 2px line. */}\n                {activeIndex !== null && (\n                  <motion.line\n                    initial={false}\n                    animate={{ x1: toX(activeIndex), x2: toX(activeIndex) }}\n                    transition={spring(450, 32)}\n                    y1={plotTop - 4}\n                    y2={plotBottom}\n                    stroke=\"currentColor\"\n                    strokeWidth={1}\n                    className=\"text-faint\"\n                  />\n                )}\n\n                {view === \"bars\"\n                  ? visible.map((entry, position) => {\n                      const slot = plotWidth / Math.max(length, 1);\n                      const width = Math.max(\n                        Math.min((slot * 0.8) / visible.length - 2, BAR_MAX_W),\n                        1,\n                      );\n                      const groupWidth = width * visible.length + 2 * (visible.length - 1);\n                      const colour = colourOf(entry.name);\n                      return (\n                        <g key={entry.name}>\n                          {entry.data.map((point, index) => {\n                            const x = toX(index) - groupWidth / 2 + position * (width + 2);\n                            return (\n                              <motion.path\n                                key={point.end}\n                                d={columnPath(x, toY(point.value), width, plotBottom)}\n                                initial={\n                                  reduceMotion\n                                    ? false\n                                    : { d: columnPath(x, plotBottom, width, plotBottom) }\n                                }\n                                animate={{\n                                  d: columnPath(x, toY(point.value), width, plotBottom),\n                                  opacity:\n                                    activeIndex === null || activeIndex === index ? 1 : 0.4,\n                                }}\n                                transition={spring(380, 30)}\n                                fill={colour}\n                              />\n                            );\n                          })}\n                        </g>\n                      );\n                    })\n                  : visible.map((entry) => {\n                      const path = splinePath(\n                        entry.data.map((point, index) => ({\n                          x: toX(index),\n                          y: toY(point.value),\n                        })),\n                      );\n                      return (\n                        <motion.path\n                          key={entry.name}\n                          /*\n                           * `d` is set as an attribute as well as animated:\n                           * Motion morphs from what is already on the element,\n                           * so an animate-only path renders nothing until the\n                           * first frame, which is every server render.\n                           */\n                          d={path}\n                          initial={false}\n                          animate={{ d: path }}\n                          transition={reduceMotion ? { duration: 0 } : { duration: 0.6, ease: EASE }}\n                          fill=\"none\"\n                          stroke={colourOf(entry.name)}\n                          strokeWidth={2}\n                          strokeLinecap=\"round\"\n                          strokeLinejoin=\"round\"\n                        />\n                      );\n                    })}\n\n                {/* End-of-line labels: identity without colour-matching. */}\n                {view === \"curve\" &&\n                  endLabels.map((label) => (\n                    <g key={`end-${label.name}`}>\n                      {Math.abs(label.y - label.anchor) > 1 && (\n                        <line\n                          x1={plotLeft + plotWidth}\n                          y1={label.anchor}\n                          x2={plotLeft + plotWidth + 8}\n                          y2={label.y}\n                          stroke={colourOf(label.name)}\n                          strokeWidth={1}\n                          opacity={0.5}\n                        />\n                      )}\n                      <circle\n                        cx={plotLeft + plotWidth}\n                        cy={label.anchor}\n                        r={3.5}\n                        fill={colourOf(label.name)}\n                        className=\"stroke-card\"\n                        strokeWidth={2}\n                      />\n                      <text\n                        x={plotLeft + plotWidth + 11}\n                        y={label.y}\n                        dominantBaseline=\"middle\"\n                        className=\"fill-foreground/55 text-[11px] font-medium\"\n                      >\n                        {label.name.replace(/^clients\\s+/i, \"\")}\n                      </text>\n                    </g>\n                  ))}\n\n                {/* Markers on the read point, ringed in the surface colour. */}\n                {view === \"curve\" &&\n                  activeIndex !== null &&\n                  visible.map((entry) => {\n                    const point = entry.data[Math.min(activeIndex, entry.data.length - 1)];\n                    if (!point) return null;\n                    return (\n                      <motion.circle\n                        key={`dot-${entry.name}`}\n                        initial={false}\n                        animate={{ cx: toX(activeIndex), cy: toY(point.value) }}\n                        transition={spring(450, 30)}\n                        r={4.5}\n                        fill={colourOf(entry.name)}\n                        className=\"stroke-card\"\n                        strokeWidth={2}\n                      />\n                    );\n                  })}\n              </svg>\n            )}\n\n            {/* Tooltip: every series at that date, values leading. */}\n            <AnimatePresence>\n              {activeIndex !== null && activeBucket && size.width > 0 && (\n                <motion.div\n                  className=\"pointer-events-none absolute z-50\"\n                  initial={{ opacity: 0, scale: 0.96 }}\n                  animate={{ left: toX(activeIndex), top: plotTop, opacity: 1, scale: 1 }}\n                  exit={{ opacity: 0, scale: 0.96 }}\n                  transition={{\n                    left: spring(450, 32),\n                    opacity: { duration: 0.15 },\n                    scale: { duration: 0.15 },\n                  }}\n                  style={{\n                    translate:\n                      toX(activeIndex) > plotLeft + plotWidth / 2\n                        ? \"calc(-100% - 12px) 0\"\n                        : \"12px 0\",\n                  }}\n                >\n                  <div className=\"min-w-[150px] rounded-xl border border-rule bg-popover/95 px-3.5 py-2.5 shadow-[0_8px_24px_color-mix(in_oklab,var(--ink)_12%,transparent)] backdrop-blur-md\">\n                    <p className=\"whitespace-nowrap text-[11px] font-bold uppercase tracking-[0.1em] text-dim\">\n                      {formatBucketRange(activeBucket)}\n                    </p>\n                    <div className=\"mt-1.5 space-y-1\">\n                      {bucketed.map((entry) => (\n                        <div\n                          key={entry.name}\n                          className=\"flex items-center justify-between gap-4 whitespace-nowrap text-[13px]\"\n                        >\n                          <span className=\"flex items-center gap-1.5 text-[12px] text-dim\">\n                            <span\n                              aria-hidden\n                              className=\"h-[3px] w-3 rounded-full\"\n                              style={{ background: colourOf(entry.name) }}\n                            />\n                            {entry.name}\n                          </span>\n                          <span className=\"font-semibold tabular-nums text-ink\">\n                            {formatCount(\n                              entry.data[Math.min(activeIndex, entry.data.length - 1)]?.value ?? 0,\n                            )}\n                          </span>\n                        </div>\n                      ))}\n                    </div>\n                  </div>\n                </motion.div>\n              )}\n            </AnimatePresence>\n          </div>\n\n          {/* The same numbers without the chart, for screen readers. A table\n              keeps its content width whatever `sr-only` sets, so the hiding\n              is done by a wrapper that can actually shrink to 1px. */}\n          <div className=\"sr-only\">\n            <table id={`${reactId}-table`}>\n              <caption>{`${title}: ${grainNote} over ${selected.label.toLowerCase()}`}</caption>\n              <thead>\n                <tr>\n                  <th scope=\"col\">Period</th>\n                  {bucketed.map((entry) => (\n                    <th key={entry.name} scope=\"col\">\n                      {entry.name}\n                    </th>\n                  ))}\n                </tr>\n              </thead>\n              <tbody>\n                {bucketed[0].data.map((point, index) => (\n                  <tr key={point.end}>\n                    <th scope=\"row\">{formatBucketRange(point)}</th>\n                    {bucketed.map((entry) => (\n                      <td key={entry.name}>{formatCount(entry.data[index]?.value ?? 0)}</td>\n                    ))}\n                  </tr>\n                ))}\n              </tbody>\n            </table>\n          </div>\n        </>\n      )}\n    </div>\n  );\n}\n\nexport default PipelineChart;\n",
      "type": "registry:block"
    }
  ],
  "meta": {
    "kind": "pattern",
    "whenToUse": "Use to compare a few daily counts over a reader-chosen window, where each line needs its own figure and change against the window before. Not for a single KPI with a sparkline (use a stat tile), for more than about five series, or for non-time categorical comparisons (use a bar chart).",
    "origin": {
      "project": "180Connect",
      "path": "src/components/ui/series-line-chart-card.tsx (ViewToggle from src/components/ui/metric-controls.tsx); used as \"Contacted, replied, converted\" in src/components/dashboard/performance-section.tsx"
    },
    "credits": []
  },
  "type": "registry:block"
}
