{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "income-spending-chart",
  "title": "Income vs spending chart",
  "description": "A financial history chart with a smooth trend strip, paired segmented bars, signed net results and year tooltips.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "registry/items/income-spending-chart/income-spending-chart.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport { motion, useReducedMotionConfig } from \"motion/react\";\n\nimport { formatCompactGbp, formatGbp } from \"./financial-history-format\";\nimport type { FinancialYear } from \"./financial-history-types\";\nexport type { FinancialYear } from \"./financial-history-types\";\nimport {\n  calculateNiceYAxis,\n  DEFICIT,\n  EXPENDITURE,\n  INCOME,\n  SURPLUS,\n} from \"./financial-history-parts\";\nimport { TimelineOverviewScrubber } from \"./timeline-overview-scrubber\";\nimport { formatUkDate } from \"./financial-history-format\";\n\nconst MAX_BARREL_STICKS = 36;\nconst MAX_NET_STICKS = 10;\n\nexport type IncomeSpendingChartProps = {\n  years: FinancialYear[];\n  showOverview?: boolean;\n  animated?: boolean;\n};\nexport function IncomeSpendingChart({ years, showOverview = true, animated = true }: IncomeSpendingChartProps) {\n  const reducedMotion = useReducedMotionConfig();\n\n  const containerRef = useRef<HTMLDivElement>(null);\n  const [hasEnteredView, setHasEnteredView] = useState(false);\n  const peak = Math.max(0, ...years.flatMap((year) => [year.income ?? 0, year.expenditure ?? 0]));\n  const peakNet = Math.max(0, ...years.map((year) => Math.abs(year.net ?? 0)));\n  const visible = !animated || reducedMotion || hasEnteredView;\n\n  useEffect(() => {\n    const node = containerRef.current;\n    if (!node) return;\n\n    if (typeof IntersectionObserver === \"undefined\") {\n      const frame = requestAnimationFrame(() => setHasEnteredView(true));\n      return () => cancelAnimationFrame(frame);\n    }\n\n    const observer = new IntersectionObserver(\n      ([entry]) => {\n        if (entry?.isIntersecting) {\n          setHasEnteredView(true);\n          observer.disconnect();\n        }\n      },\n      { threshold: 0.1 },\n    );\n    observer.observe(node);\n\n    const timer = setTimeout(() => setHasEnteredView(true), 1200);\n    return () => {\n      observer.disconnect();\n      clearTimeout(timer);\n    };\n  }, []);\n\n  const yAxis = useMemo(() => calculateNiceYAxis(peak), [peak]);\n  // One year at a time: pointing at any of a year's three marks — or its\n  // label — picks the whole year, so its figures read together in one tooltip\n  // instead of three separate hovers.\n  const [hovered, setHovered] = useState<number | null>(null);\n  const hoverProps = (index: number) => ({\n    onPointerEnter: () => setHovered(index),\n  });\n  const dimmed = (index: number) => hovered !== null && hovered !== index;\n\n  if (years.length === 0) return null;\n\n  const safeYMax = yAxis.max > 0 ? yAxis.max : 1;\n  const safePeakNet = peakNet > 0 ? peakNet : 1;\n\n  return (\n    <div ref={containerRef} className=\"@container w-full min-w-0 select-none font-body\">\n      {showOverview && years.length > 1 && (\n        <div className=\"mb-4\">\n          <TimelineOverviewScrubber years={years} />\n        </div>\n      )}\n\n      <div className=\"flex items-center justify-end\">\n        <ul className=\"flex flex-wrap items-center gap-x-4 gap-y-1.5\" aria-label=\"Chart legend\">\n          <li className=\"flex items-center gap-2 text-[12px] text-dim\">\n            <span aria-hidden=\"true\" className=\"flex flex-col gap-[1.5px]\">\n              <span className=\"h-[2px] w-3 rounded-full\" style={{ backgroundColor: INCOME }} />\n              <span className=\"h-[2px] w-3 rounded-full\" style={{ backgroundColor: INCOME }} />\n              <span className=\"h-[2px] w-3 rounded-full\" style={{ backgroundColor: INCOME }} />\n            </span>\n            Income\n          </li>\n          <li className=\"flex items-center gap-2 text-[12px] text-dim\">\n            <span aria-hidden=\"true\" className=\"flex flex-col gap-[1.5px]\">\n              <span className=\"h-[2px] w-3 rounded-full\" style={{ backgroundColor: EXPENDITURE }} />\n              <span className=\"h-[2px] w-3 rounded-full\" style={{ backgroundColor: EXPENDITURE }} />\n              <span className=\"h-[2px] w-3 rounded-full\" style={{ backgroundColor: EXPENDITURE }} />\n            </span>\n            Spending\n          </li>\n        </ul>\n      </div>\n\n      <div onPointerLeave={() => setHovered(null)}>\n      \n      <div className=\"relative mt-4 pt-2.5\">\n        <div className=\"flex items-end\">\n          \n          <div className=\"relative h-[214px] w-14 shrink-0 sm:w-16\" aria-hidden=\"true\">\n            {yAxis.ticks.map((tick) => {\n              const topPercent = (1 - tick / safeYMax) * 100;\n              return (\n                <div\n                  key={tick}\n                  className=\"absolute right-2.5 -translate-y-1/2 flex items-center justify-end\"\n                  style={{ top: `${Number(topPercent.toFixed(6))}%` }}\n                >\n                  <span className=\"font-mono text-[10.5px] tabular-nums text-faint\">\n                    {formatCompactGbp(tick)}\n                  </span>\n                </div>\n              );\n            })}\n          </div>\n\n          <div className=\"relative h-[214px] flex-1 min-w-0\">\n            \n            <div className=\"pointer-events-none absolute inset-0\" aria-hidden=\"true\">\n              {yAxis.ticks.map((tick) => {\n                const topPercent = (1 - tick / safeYMax) * 100;\n                const isZero = tick === 0;\n                return (\n                  <div\n                    key={`grid-${tick}`}\n                    className={`absolute inset-x-0 h-px ${\n                      isZero ? \"bg-rule\" : \"bg-rule-soft/60\"\n                    }`}\n                    style={{ top: `${Number(topPercent.toFixed(6))}%` }}\n                  />\n                );\n              })}\n            </div>\n\n            <div className=\"relative flex h-full items-end gap-2\">\n              {years.map((year, index) => {\n                const hasIncome = year.income !== null && year.income > 0;\n                const hasExpenditure = year.expenditure !== null && year.expenditure > 0;\n\n                const incomeStickCount = hasIncome\n                  ? Math.max(1, Math.min(MAX_BARREL_STICKS, Math.round((year.income! / safeYMax) * MAX_BARREL_STICKS)))\n                  : 0;\n\n                const expStickCount = hasExpenditure\n                  ? Math.max(1, Math.min(MAX_BARREL_STICKS, Math.round((year.expenditure! / safeYMax) * MAX_BARREL_STICKS)))\n                  : 0;\n\n                return (\n                  <div\n                    key={year.periodEnd}\n                    aria-label={`${year.label}: income ${formatGbp(year.income)}, spending ${formatGbp(year.expenditure)}${\n                      year.net !== null\n                        ? `, ${year.net >= 0 ? \"surplus\" : \"deficit\"} ${formatGbp(Math.abs(year.net))}`\n                        : \"\"\n                    }`}\n                    role=\"button\"\n                    tabIndex={0}\n                    onClick={() => setHovered(index)}\n                    onKeyDown={(event) => {\n                      if (event.key === \"Enter\" || event.key === \" \") {\n                        event.preventDefault();\n                        setHovered(index);\n                      }\n                    }}\n                    onFocus={() => setHovered(index)}\n                    onBlur={() => setHovered(null)}\n                    {...hoverProps(index)}\n                    className=\"relative flex h-full min-w-0 flex-1 flex-col items-center justify-end rounded-t-panel px-1 outline-none focus-visible:ring-2 focus-visible:ring-lead-mid\"\n                  >\n                    {hovered === index && (\n                      <YearTooltip\n                        year={year}\n                        // Beside the column, never over it: the tooltip is read\n                        // against the bars it describes. Right of the first half\n                        // of the years, left of the second, so it stays inside\n                        // the plot.\n                        side={index < years.length / 2 ? \"right\" : \"left\"}\n                      />\n                    )}\n                    \n                    <div\n                      className=\"flex items-end gap-1 pb-0.5 transition-opacity duration-150 @sm:gap-2\"\n                      style={{ opacity: dimmed(index) ? 0.35 : 1 }}\n                    >\n                      \n                      <div className=\"flex h-[214px] flex-col-reverse justify-start gap-[2px]\" aria-hidden=\"true\">\n                        {hasIncome ? (\n                          Array.from({ length: incomeStickCount }, (_, stickIdx) => (\n                            <motion.div\n                              key={`inc-stick-${stickIdx}`}\n                              initial={animated && !reducedMotion ? { opacity: 0, scaleX: 0.6, originX: 0.5 } : false}\n                              animate={{\n                                opacity: visible ? 1 : 0,\n                                scaleX: visible ? 1 : 0.6,\n                              }}\n                              transition={{\n                                duration: 0.2,\n                                delay: index * 0.05 + stickIdx * 0.008,\n                                ease: [0.16, 1, 0.3, 1],\n                              }}\n                              className=\"h-[4px] w-[clamp(6px,2cqw,18px)] rounded-inset transition-all duration-150 @sm:w-[22px]\"\n                              style={{ backgroundColor: INCOME }}\n                            />\n                          ))\n                        ) : year.income !== null ? (\n                          <span className=\"h-[2px] w-[clamp(6px,2cqw,18px)] rounded-full bg-rule-soft @sm:w-[22px]\" />\n                        ) : null}\n                      </div>\n\n                      <div className=\"flex h-[214px] flex-col-reverse justify-start gap-[2px]\" aria-hidden=\"true\">\n                        {hasExpenditure ? (\n                          Array.from({ length: expStickCount }, (_, stickIdx) => (\n                            <motion.div\n                              key={`exp-stick-${stickIdx}`}\n                              initial={animated && !reducedMotion ? { opacity: 0, scaleX: 0.6, originX: 0.5 } : false}\n                              animate={{\n                                opacity: visible ? 1 : 0,\n                                scaleX: visible ? 1 : 0.6,\n                              }}\n                              transition={{\n                                duration: 0.2,\n                                delay: index * 0.05 + 0.02 + stickIdx * 0.008,\n                                ease: [0.16, 1, 0.3, 1],\n                              }}\n                              className=\"h-[4px] w-[clamp(6px,2cqw,18px)] rounded-inset transition-all duration-150 @sm:w-[22px]\"\n                              style={{ backgroundColor: EXPENDITURE }}\n                            />\n                          ))\n                        ) : year.expenditure !== null ? (\n                          <span className=\"h-[2px] w-[clamp(6px,2cqw,18px)] rounded-full bg-rule-soft @sm:w-[22px]\" />\n                        ) : null}\n                      </div>\n                    </div>\n                  </div>\n                );\n              })}\n            </div>\n          </div>\n        </div>\n      </div>\n\n      <div className=\"flex items-start pt-1.5\">\n        <div className=\"flex w-14 shrink-0 items-start justify-end pr-2.5 pt-1 sm:w-16\" aria-hidden=\"true\">\n          <span className=\"font-mono text-[10px] font-medium tracking-wider text-faint uppercase\">\n            Net\n          </span>\n        </div>\n        <div className=\"flex min-h-[82px] flex-1 min-w-0 items-start gap-2\">\n          {years.map((year, index) => {\n            const net = year.net;\n            const hasNet = net !== null && Math.abs(net) > 0;\n            const netStickCount = hasNet\n              ? Math.max(1, Math.min(MAX_NET_STICKS, Math.round((Math.abs(net) / safePeakNet) * MAX_NET_STICKS)))\n              : 0;\n            const netColor = net !== null && net >= 0 ? SURPLUS : DEFICIT;\n\n            return (\n              <div\n                key={year.periodEnd}\n                {...hoverProps(index)}\n                className=\"flex flex-1 flex-col items-center justify-start rounded-b-panel px-1 pb-1 transition-opacity duration-150\"\n                style={{ opacity: dimmed(index) ? 0.35 : 1 }}\n              >\n                \n                <div className=\"flex min-h-[58px] flex-col justify-start gap-[2px]\" aria-hidden=\"true\">\n                  {hasNet ? (\n                    Array.from({ length: netStickCount }, (_, stickIdx) => (\n                      <motion.div\n                        key={`net-stick-${stickIdx}`}\n                        initial={animated && !reducedMotion ? { opacity: 0, scaleX: 0.6, originX: 0.5 } : false}\n                        animate={{\n                          opacity: visible ? 1 : 0,\n                          scaleX: visible ? 1 : 0.6,\n                        }}\n                        transition={{\n                          duration: 0.18,\n                          delay: index * 0.05 + 0.1 + stickIdx * 0.012,\n                          ease: [0.16, 1, 0.3, 1],\n                        }}\n                        className=\"h-[4px] w-[clamp(8px,2.5cqw,20px)] rounded-inset transition-all duration-150 @sm:w-[24px]\"\n                        style={{ backgroundColor: netColor }}\n                      />\n                    ))\n                  ) : (\n                    <div className=\"h-[4px] w-[clamp(8px,2.5cqw,20px)] @sm:w-[24px]\" />\n                  )}\n                </div>\n\n                <span\n                  className={`mt-1 font-mono text-[9px] @sm:text-[11px] tabular-nums transition-colors ${\n                    net === null ? \"text-faint\" : net >= 0 ? \"text-go font-medium\" : \"text-stop font-medium\"\n                  }`}\n                >\n                  {net === null\n                    ? \"—\"\n                    : `${net >= 0 ? \"+\" : \"−\"}${formatCompactGbp(Math.abs(net))}`}\n                </span>\n              </div>\n            );\n          })}\n        </div>\n      </div>\n\n      <div className=\"mt-1 flex items-center\">\n        <div className=\"w-14 shrink-0 sm:w-16\" aria-hidden=\"true\" />\n        <div className=\"flex flex-1 min-w-0 gap-2\">\n          {years.map((year, index) => (\n            <span\n              key={year.periodEnd}\n              {...hoverProps(index)}\n              className={`flex-1 text-center text-[11.5px] transition-colors ${\n                hovered === index ? \"font-semibold text-ink\" : \"text-dim\"\n              }`}\n            >\n              {year.label}\n            </span>\n          ))}\n        </div>\n      </div>\n      </div>\n    </div>\n  );\n}\n\nfunction YearTooltip({\n  year,\n  side,\n}: {\n  year: FinancialYear;\n  side: \"left\" | \"right\";\n}) {\n  const periodEnd = formatUkDate(year.periodEnd);\n  const net = year.net;\n\n  return (\n    <div\n      aria-hidden=\"true\"\n      className={`pointer-events-none absolute top-0 z-20 w-max max-w-[calc(100cqw-1rem)] rounded-panel border border-rule bg-card px-3 py-2.5 shadow-lg ${\n        side === \"right\" ? \"left-0 @lg:left-full @lg:ml-1\" : \"right-0 @lg:right-full @lg:mr-1\"\n      }`}\n    >\n      <p className=\"text-[12.5px] font-semibold text-ink\">{year.label}</p>\n      <p className=\"text-[11px] text-faint\">Year ending {periodEnd}</p>\n      <dl className=\"mt-2 space-y-1 text-[12.5px]\">\n        <TooltipRow colour={INCOME} label=\"Income\" value={formatGbp(year.income)} />\n        <TooltipRow\n          colour={EXPENDITURE}\n          label=\"Spending\"\n          value={formatGbp(year.expenditure)}\n        />\n        <div className=\"mt-1.5 border-t border-rule-soft pt-1.5\">\n          <TooltipRow\n            colour={net === null ? undefined : net >= 0 ? SURPLUS : DEFICIT}\n            label={net === null ? \"Net\" : net >= 0 ? \"Surplus\" : \"Deficit\"}\n            value={\n              net === null\n                ? \"Not reported\"\n                : `${net >= 0 ? \"+\" : \"−\"}${formatGbp(Math.abs(net))}`\n            }\n            valueClassName={\n              net === null ? \"text-faint\" : net >= 0 ? \"text-go\" : \"text-stop\"\n            }\n          />\n        </div>\n      </dl>\n    </div>\n  );\n}\n\nfunction TooltipRow({\n  colour,\n  label,\n  value,\n  valueClassName = \"text-ink\",\n}: {\n  colour?: string;\n  label: string;\n  value: string;\n  valueClassName?: string;\n}) {\n  return (\n    <div className=\"flex items-center justify-between gap-4\">\n      <dt className=\"flex items-center gap-1.5 text-dim\">\n        <span\n          aria-hidden=\"true\"\n          className=\"size-2 shrink-0 rounded-inset\"\n          style={{ backgroundColor: colour ?? \"transparent\" }}\n        />\n        {label}\n      </dt>\n      <dd className={`font-body font-semibold tabular-nums ${valueClassName}`}>\n        {value}\n      </dd>\n    </div>\n  );\n}\n\n",
      "type": "registry:block"
    },
    {
      "path": "registry/items/income-spending-chart/financial-history-format.ts",
      "content": "const GBP_FORMATTER = new Intl.NumberFormat(\"en-GB\", {\n  style: \"currency\",\n  currency: \"GBP\",\n  maximumFractionDigits: 0,\n});\n\n/** Formats a monetary number into standard GBP, or returns \"Not disclosed\" if null/undefined. */\nexport function formatGbp(amount: number | null | undefined): string {\n  if (amount === null || amount === undefined || Number.isNaN(amount)) {\n    return \"Not disclosed\";\n  }\n  return GBP_FORMATTER.format(amount);\n}\n\n/** Formats a monetary number into a compact string (e.g. £450k, £1.2m). */\nexport function formatCompactGbp(amount: number | null | undefined): string {\n  if (amount === null || amount === undefined || Number.isNaN(amount)) {\n    return \"Not disclosed\";\n  }\n  const abs = Math.abs(amount);\n  const sign = amount < 0 ? \"-\" : \"\";\n  if (abs >= 1_000_000) {\n    return `${sign}£${(abs / 1_000_000).toFixed(1).replace(/\\.0$/, \"\")}m`;\n  }\n  if (abs >= 1_000) {\n    return `${sign}£${Math.round(abs / 1_000)}k`;\n  }\n  return `${sign}£${abs.toLocaleString(\"en-GB\")}`;\n}\n\n\nexport function formatUkDate(value: string) {\n  const date = new Date(value.length === 10 ? value + \"T00:00:00Z\" : value);\n  return Number.isNaN(date.getTime()) ? \"Unknown date\" : date.toLocaleDateString(\"en-GB\", { day: \"numeric\", month: \"long\", year: \"numeric\", timeZone: \"UTC\" });\n}\n",
      "type": "registry:block"
    },
    {
      "path": "registry/items/income-spending-chart/financial-history-parts.tsx",
      "content": "export const INCOME = \"var(--lead)\";\nexport const EXPENDITURE = \"var(--ramp-orange)\";\nexport const SURPLUS = \"var(--go)\";\nexport const DEFICIT = \"var(--stop)\";\nexport function calculateNiceYAxis(\n  maxValue: number,\n  targetTicks: number = 4,\n): { max: number; ticks: number[] } {\n  if (maxValue <= 0 || !Number.isFinite(maxValue)) {\n    return { max: 1000, ticks: [1000, 500, 0] };\n  }\n  if (maxValue < 10) {\n    return { max: 10, ticks: [10, 5, 0] };\n  }\n\n  const roughStep = maxValue / Math.max(1, targetTicks);\n  const stepPower = Math.pow(10, Math.floor(Math.log10(roughStep)));\n  const stepFraction = roughStep / stepPower;\n\n  let niceMultiplier = 1;\n  if (stepFraction > 7.5) {\n    niceMultiplier = 10;\n  } else if (stepFraction > 3.5) {\n    niceMultiplier = 5;\n  } else if (stepFraction > 2 && stepPower >= 10_000) {\n    niceMultiplier = 2.5;\n  } else if (stepFraction > 1.4) {\n    niceMultiplier = 2;\n  } else {\n    niceMultiplier = 1;\n  }\n\n  const step = niceMultiplier * stepPower;\n  const niceMax = Math.ceil(maxValue / step) * step;\n\n  const ticks: number[] = [];\n  const count = Math.round(niceMax / step);\n  for (let i = count; i >= 0; i--) {\n    ticks.push(Math.round(i * step));\n  }\n\n  return { max: niceMax, ticks };\n}\n",
      "type": "registry:block"
    },
    {
      "path": "registry/items/income-spending-chart/financial-history-types.ts",
      "content": "export type FinancialYear = {\n  label: string;\n  periodEnd: string;\n  income: number | null;\n  expenditure: number | null;\n  net: number | null;\n};\n",
      "type": "registry:block"
    },
    {
      "path": "registry/items/income-spending-chart/timeline-overview-scrubber.tsx",
      "content": "\"use client\";\n\nimport { useId, useMemo, useState } from \"react\";\n\nimport type { FinancialYear } from \"./financial-history-types\";\nimport {\n  calculateTimelineOverviewPoints,\n  type TrendMetric,\n} from \"./financial-history-math\";\nimport { INCOME } from \"./financial-history-parts\";\n\nexport type { TrendMetric };\n\ninterface TimelineOverviewScrubberProps {\n  years: FinancialYear[];\n  hovered?: number | null;\n  onHover?: (index: number | null) => void;\n  className?: string;\n}\n\nexport function TimelineOverviewScrubber({\n  years,\n  className = \"\",\n}: TimelineOverviewScrubberProps) {\n  const gradientId = useId().replace(/:/g, \"\");\n  const [metric, setMetric] = useState<TrendMetric>(\"income\");\n\n  const length = years.length;\n\n  // Calculate curve points based on active metric\n  const { curvePoints, splineLine, splineFill, zeroYPercent } = useMemo(\n    () => calculateTimelineOverviewPoints(years, metric),\n    [years, metric],\n  );\n\n  if (length < 2) return null;\n\n  return (\n    <div className={`select-none ${className}`}>\n      \n      <div className=\"flex items-center pb-2\">\n        <div\n          role=\"group\"\n          aria-label=\"Metric view\"\n          className=\"inline-flex items-center rounded-inset bg-paper-sunk/70 p-0.5 border border-rule-soft/60\"\n        >\n          <button\n            type=\"button\"\n                        aria-pressed={metric === \"income\"}\n            onClick={() => setMetric(\"income\")}\n            className={`rounded-inset px-2 py-0.5 font-mono text-[11px] transition-all ${\n              metric === \"income\"\n                ? \"bg-card text-ink font-semibold shadow-xs border border-rule-soft/60\"\n                : \"text-dim hover:text-ink\"\n            }`}\n          >\n            Income\n          </button>\n          <button\n            type=\"button\"\n                        aria-pressed={metric === \"net\"}\n            onClick={() => setMetric(\"net\")}\n            className={`rounded-inset px-2 py-0.5 font-mono text-[11px] transition-all ${\n              metric === \"net\"\n                ? \"bg-card text-ink font-semibold shadow-xs border border-rule-soft/60\"\n                : \"text-dim hover:text-ink\"\n            }`}\n          >\n            Net result\n          </button>\n        </div>\n      </div>\n\n      <div className=\"relative h-[64px] sm:h-[76px] w-full overflow-hidden rounded-inset bg-card border border-rule-soft\">\n        \n        <svg\n          className=\"absolute inset-0 h-full w-full overflow-visible\"\n          viewBox=\"0 0 100 100\"\n          preserveAspectRatio=\"none\"\n          aria-hidden=\"true\"\n        >\n          <defs>\n            <linearGradient\n              id={`${gradientId}-income-wash`}\n              x1=\"0\"\n              y1=\"0\"\n              x2=\"0\"\n              y2=\"1\"\n            >\n              <stop offset=\"0%\" stopColor={INCOME} stopOpacity={0.16} />\n              <stop offset=\"80%\" stopColor={INCOME} stopOpacity={0.03} />\n              <stop offset=\"100%\" stopColor={INCOME} stopOpacity={0} />\n            </linearGradient>\n            <linearGradient\n              id={`${gradientId}-lead-wash`}\n              x1=\"0\"\n              y1=\"0\"\n              x2=\"0\"\n              y2=\"1\"\n            >\n              <stop offset=\"0%\" stopColor=\"var(--lead)\" stopOpacity={0.14} />\n              <stop offset=\"80%\" stopColor=\"var(--lead)\" stopOpacity={0.03} />\n              <stop offset=\"100%\" stopColor=\"var(--lead)\" stopOpacity={0} />\n            </linearGradient>\n          </defs>\n\n          {zeroYPercent !== null && (\n            <line\n              x1=\"0\"\n              x2=\"100\"\n              y1={zeroYPercent}\n              y2={zeroYPercent}\n              stroke=\"var(--rule)\"\n              strokeDasharray=\"3 3\"\n              vectorEffect=\"non-scaling-stroke\"\n            />\n          )}\n\n          <path\n            d={splineFill}\n            fill={`url(#${gradientId}-${metric === \"income\" ? \"income-wash\" : \"lead-wash\"})`}\n          />\n\n          <path\n            d={splineLine}\n            fill=\"none\"\n            // `style`, not `stroke={…}`: `INCOME` is a CSS `light-dark()` pair\n            // and a presentation attribute does not parse one.\n            style={{ stroke: metric === \"income\" ? INCOME : \"var(--lead)\" }}\n            strokeWidth={1.8}\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n            vectorEffect=\"non-scaling-stroke\"\n          />\n        </svg>\n\n        <div className=\"absolute inset-0 flex\">\n          {years.map((year, index) => {\n            const pt = curvePoints[index];\n\n            return (\n              <div\n                key={year.periodEnd}\n                className=\"relative flex h-full flex-1 flex-col items-center justify-end pb-1.5\"\n              >\n                \n                {pt && (\n                  <div\n                    className=\"pointer-events-none absolute -translate-x-1/2 -translate-y-1/2\"\n                    style={{ left: \"50%\", top: `${Number(pt.y.toFixed(6))}%` }}\n                  >\n                    <span className=\"block size-1.5 rounded-full bg-lead/70\" />\n                  </div>\n                )}\n\n                <span className=\"font-mono text-[11px] tabular-nums text-faint\">\n                  {year.label}\n                </span>\n              </div>\n            );\n          })}\n        </div>\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:block"
    },
    {
      "path": "registry/items/income-spending-chart/financial-history-math.ts",
      "content": "import type { FinancialYear } from \"./financial-history-types.ts\";\n\nexport type TrendMetric = \"income\" | \"net\";\n\nexport interface TimelineOverviewCalculation {\n  curvePoints: { x: number; y: number }[];\n  splineLine: string;\n  splineFill: string;\n  zeroYPercent: number | null;\n}\n\nconst TOP_Y = 10;\nconst BOTTOM_Y = 68;\n\nconst MIN_SPAN_OF_PEAK = 0.1;\nexport const NET_ZERO_Y = 40;\n\nexport function calculateTimelineOverviewPoints(\n  years: FinancialYear[],\n  metric: TrendMetric,\n): TimelineOverviewCalculation {\n  const length = years.length;\n  if (length < 2) {\n    return { curvePoints: [], splineLine: \"\", splineFill: \"\", zeroYPercent: null };\n  }\n\n  if (metric === \"income\") {\n    const incomes = years.map((y) => y.income ?? 0);\n    const maxIncome = Math.max(...incomes, 1);\n    const minIncome = Math.min(...incomes);\n    const span = Math.max(maxIncome - minIncome, maxIncome * MIN_SPAN_OF_PEAK);\n    // Centre the data in the span, so a small real change sits mid-strip\n    // rather than pinned to one edge.\n    const floor = (maxIncome + minIncome) / 2 - span / 2;\n    const rangeY = BOTTOM_Y - TOP_Y;\n\n    const pts = years.map((y, i) => {\n      const val = y.income ?? 0;\n      const x = ((i + 0.5) / length) * 100;\n      const yCoord = BOTTOM_Y - ((val - floor) / span) * rangeY;\n      return { x, y: Math.max(TOP_Y, Math.min(BOTTOM_Y, yCoord)) };\n    });\n\n    const { line, fill } = buildMonotoneSplinePath(pts);\n    return { curvePoints: pts, splineLine: line, splineFill: fill, zeroYPercent: null };\n  }\n\n  // Net result mode (surplus/deficit)\n  const nets = years.map((y) => y.net ?? 0);\n  const absMax = Math.max(...nets.map(Math.abs), 1);\n  const midY = NET_ZERO_Y;\n  const maxOffset = Math.min(midY - TOP_Y, BOTTOM_Y - midY);\n\n  const pts = years.map((y, i) => {\n    const netVal = y.net ?? 0;\n    const x = ((i + 0.5) / length) * 100;\n    const yCoord = midY - (netVal / absMax) * maxOffset;\n    return { x, y: Math.max(TOP_Y, Math.min(BOTTOM_Y, yCoord)) };\n  });\n\n  const { line, fill } = buildMonotoneSplinePath(pts);\n  return { curvePoints: pts, splineLine: line, splineFill: fill, zeroYPercent: midY };\n}\n\nexport function buildMonotoneSplinePath(\n  pts: { x: number; y: number }[],\n): { line: string; fill: string } {\n  const n = pts.length;\n  if (n < 1) return { line: \"\", fill: \"\" };\n  if (n === 1) {\n    const y = Math.max(0, Math.min(100, pts[0].y));\n    const line = `M 0 ${y.toFixed(2)} L 100 ${y.toFixed(2)}`;\n    const fill = `${line} L 100 100 L 0 100 Z`;\n    return { line, fill };\n  }\n\n  // 1. Calculate secants (slopes) & dx\n  const dxs = new Float64Array(n - 1);\n  const deltas = new Float64Array(n - 1);\n  for (let i = 0; i < n - 1; i++) {\n    dxs[i] = pts[i + 1].x - pts[i].x;\n    deltas[i] = dxs[i] === 0 ? 0 : (pts[i + 1].y - pts[i].y) / dxs[i];\n  }\n\n  // 2. Tangents\n  const m = new Float64Array(n);\n  for (let i = 1; i < n - 1; i++) {\n    if (deltas[i - 1] * deltas[i] <= 0) {\n      m[i] = 0;\n    } else {\n      const hPrev = dxs[i - 1];\n      const hNext = dxs[i];\n      m[i] =\n        (3 * (hPrev + hNext)) /\n        ((2 * hNext + hPrev) / deltas[i - 1] + (hNext + 2 * hPrev) / deltas[i]);\n    }\n  }\n  m[0] = deltas[0];\n  if (deltas.length > 1 && deltas[0] * deltas[1] <= 0) m[0] = 0;\n  m[n - 1] = deltas[n - 2];\n  if (deltas.length > 1 && deltas[n - 2] * deltas[n - 3] <= 0) m[n - 1] = 0;\n\n  // 3. Fritsch-Carlson monotonicity\n  for (let i = 0; i < n - 1; i++) {\n    if (deltas[i] === 0) {\n      m[i] = 0;\n      m[i + 1] = 0;\n    } else {\n      const alpha = m[i] / deltas[i];\n      const beta = m[i + 1] / deltas[i];\n      const dist = alpha * alpha + beta * beta;\n      if (dist > 9) {\n        const tau = 3 / Math.sqrt(dist);\n        m[i] = tau * alpha * deltas[i];\n        m[i + 1] = tau * beta * deltas[i];\n      }\n    }\n  }\n\n  // 4. Cubic Bézier segments\n  let line = `M ${pts[0].x.toFixed(2)} ${Math.max(0, Math.min(100, pts[0].y)).toFixed(2)}`;\n  for (let i = 0; i < n - 1; i++) {\n    const p0 = pts[i];\n    const p1 = pts[i + 1];\n    const dx = p1.x - p0.x;\n    const cp1x = p0.x + dx / 3;\n    const cp1y = Math.max(0, Math.min(100, p0.y + (m[i] * dx) / 3));\n    const cp2x = p1.x - dx / 3;\n    const cp2y = Math.max(0, Math.min(100, p1.y - (m[i + 1] * dx) / 3));\n    const targetY = Math.max(0, Math.min(100, p1.y));\n    line += ` C ${cp1x.toFixed(2)} ${cp1y.toFixed(2)}, ${cp2x.toFixed(2)} ${cp2y.toFixed(2)}, ${p1.x.toFixed(2)} ${targetY.toFixed(2)}`;\n  }\n\n  const fill = `${line} L ${pts[n - 1].x.toFixed(2)} 100 L ${pts[0].x.toFixed(2)} 100 Z`;\n  return { line, fill };\n}\n\n",
      "type": "registry:block"
    }
  ],
  "meta": {
    "kind": "pattern",
    "whenToUse": "Use to compare income and spending across filed years. Missing amounts remain distinct from zero; net results have a separate scale.",
    "origin": {
      "project": "180Connect",
      "path": "src/app/(app)/clients/[id]/financials/financial-history-chart.tsx"
    },
    "credits": []
  },
  "type": "registry:block"
}
