{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "forecast-ribbon-chart",
  "title": "Forecast Ribbon Chart",
  "description": "A forecast that shows its doubt: history runs into nested 50, 80 and 95% ribbons that widen with time, and scenarios ease from one shape to the next.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/new-york/forecast-ribbon-chart/forecast-ribbon-chart.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nexport interface RibbonPoint {\n  label: string;\n  value: number;\n}\n\nexport interface RibbonScenario {\n  label: string;\n  /** Growth per step, e.g. 0.03 for 3%. */\n  growth: number;\n  /** How quickly the ribbon widens, as a share of the forecast value. */\n  spread: number;\n}\n\nexport interface ForecastRibbonChartProps extends Omit<\n  React.ComponentPropsWithoutRef<\"section\">,\n  \"title\"\n> {\n  theme?: \"dark\" | \"light\";\n  title?: string;\n  subtitle?: string;\n  history?: RibbonPoint[];\n  /** Labels for the forecast steps. Its length sets how far ahead the ribbon runs. */\n  future?: string[];\n  scenarios?: RibbonScenario[];\n  /** Index of the scenario shown first. */\n  defaultScenario?: number;\n  /** Colour of the line and ribbon. */\n  color?: string;\n  /** Height of the plot, in px. */\n  height?: number;\n  formatValue?: (value: number) => string;\n  onScenarioChange?: (scenario: RibbonScenario) => void;\n}\n\nconst PALETTES = {\n  dark: {\n    card: \"#08090A\",\n    surface: \"#0F1011\",\n    border: \"rgba(255,255,255,0.08)\",\n    grid: \"rgba(255,255,255,0.05)\",\n    text: \"#F7F8F8\",\n    soft: \"#D0D6E0\",\n    sub: \"#8A8F98\",\n    faint: \"#62666D\",\n    tip: \"#161718\",\n    tipShadow: \"0 4px 24px rgba(0,0,0,0.4)\",\n    chip: \"rgba(255,255,255,0.05)\",\n    chipOn: \"rgba(255,255,255,0.1)\",\n    accent: \"#5E6AD2\",\n  },\n  light: {\n    card: \"#FFFFFF\",\n    surface: \"#F7F8F8\",\n    border: \"rgba(8,9,10,0.08)\",\n    grid: \"rgba(8,9,10,0.06)\",\n    text: \"#08090A\",\n    soft: \"#3C3F44\",\n    sub: \"#62666D\",\n    faint: \"#8A8F98\",\n    tip: \"#FFFFFF\",\n    tipShadow: \"0 3px 12px rgba(8,9,10,0.09)\",\n    chip: \"rgba(8,9,10,0.04)\",\n    chipOn: \"#FFFFFF\",\n    accent: \"#5E6AD2\",\n  },\n};\n\ntype Palette = (typeof PALETTES)[\"dark\"];\n\nconst CARD_FONT =\n  '\"Inter Variable\", Inter, \"SF Pro Display\", -apple-system, BlinkMacSystemFont, sans-serif';\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (callback) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", callback);\n      return () => query.removeEventListener(\"change\", callback);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\n/** The chart is drawn at its real width, so its text stays the same size on a phone. */\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n  const [width, setWidth] = React.useState(700);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) =>\n      setWidth(Math.max(240, Math.round(entry.contentRect.width))),\n    );\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [ref]);\n  return width;\n}\n\nfunction Stat({\n  value,\n  label,\n  pal,\n}: {\n  value: string;\n  label: string;\n  pal: Palette;\n}) {\n  return (\n    <div className=\"text-left sm:text-right\">\n      <p className=\"m-0 text-[18px] leading-[1.2] font-[510] tracking-[-0.018em] tabular-nums\">\n        {value}\n      </p>\n      <p\n        className=\"m-0 mt-0.5 text-[12px] tracking-[-0.011em]\"\n        style={{ color: pal.sub }}\n      >\n        {label}\n      </p>\n    </div>\n  );\n}\n\nfunction Pills({\n  label,\n  options,\n  value,\n  onChange,\n  pal,\n}: {\n  label: string;\n  options: string[];\n  value: number;\n  onChange: (index: number) => void;\n  pal: Palette;\n}) {\n  return (\n    <div\n      className=\"flex rounded-full p-0.5\"\n      style={{ background: pal.chip }}\n      role=\"radiogroup\"\n      aria-label={label}\n    >\n      {options.map((option, i) => (\n        <button\n          key={option}\n          type=\"button\"\n          role=\"radio\"\n          aria-checked={i === value}\n          onClick={() => onChange(i)}\n          className=\"h-7 cursor-pointer rounded-full px-3 text-[13px] font-[510] tracking-[-0.011em] transition-colors outline-none focus-visible:ring-2\"\n          style={{\n            background: i === value ? pal.chipOn : \"transparent\",\n            color: i === value ? pal.text : pal.sub,\n          }}\n        >\n          {option}\n        </button>\n      ))}\n    </div>\n  );\n}\n\nfunction Tip({\n  x,\n  y,\n  width,\n  pal,\n  children,\n}: {\n  x: number;\n  y: number;\n  width: number;\n  pal: Palette;\n  children: React.ReactNode;\n}) {\n  return (\n    <div\n      aria-hidden=\"true\"\n      className=\"pointer-events-none absolute z-10 -translate-x-1/2 rounded-lg px-2.5 py-1.5 text-[12px] tracking-[-0.011em] whitespace-nowrap\"\n      style={{\n        left: Math.max(110, Math.min(width - 110, x)),\n        top: Math.max(0, y - 42),\n        background: pal.tip,\n        color: pal.sub,\n        boxShadow: `inset 0 0 0 1px ${pal.border}, ${pal.tipShadow}`,\n      }}\n    >\n      {children}\n    </div>\n  );\n}\n\nconst HISTORY: RibbonPoint[] = [\n  [\"Jan 25\", 182],\n  [\"Feb\", 196],\n  [\"Mar\", 188],\n  [\"Apr\", 214],\n  [\"May\", 231],\n  [\"Jun\", 224],\n  [\"Jul\", 252],\n  [\"Aug\", 268],\n  [\"Sep\", 259],\n  [\"Oct\", 291],\n  [\"Nov\", 306],\n  [\"Dec\", 298],\n  [\"Jan 26\", 327],\n  [\"Feb\", 344],\n  [\"Mar\", 338],\n  [\"Apr\", 372],\n].map(([label, value]) => ({\n  label: label as string,\n  value: value as number,\n}));\n\nconst FUTURE = [\"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\n\nconst SCENARIOS: RibbonScenario[] = [\n  { label: \"Conservative\", growth: 0.012, spread: 0.03 },\n  { label: \"Base\", growth: 0.03, spread: 0.045 },\n  { label: \"Optimistic\", growth: 0.046, spread: 0.055 },\n];\n\n/** Ribbon half-widths for 50%, 80% and 95% confidence, widest first when drawn. */\nconst BANDS = [\n  { name: \"95%\", z: 1.96, opacity: 0.14 },\n  { name: \"80%\", z: 1.28, opacity: 0.2 },\n  { name: \"50%\", z: 0.67, opacity: 0.3 },\n];\n\nconst FORMAT = (n: number) => `$${Math.round(n)}k`;\n\nconst LEFT = 44;\nconst RIGHT = 10;\nconst TOP = 10;\nconst BOTTOM = 24;\n\n// Monotone cubic interpolation preserves local extrema and never overshoots the data.\nfunction curve(points: [number, number][]) {\n  if (points.length < 2) return \"\";\n  const slopes = points\n    .slice(1)\n    .map((p, i) => (p[1] - points[i][1]) / (p[0] - points[i][0]));\n  const tangents = points.map((_, i) =>\n    i === 0\n      ? slopes[0]\n      : i === points.length - 1\n        ? slopes[i - 1]\n        : slopes[i - 1] * slopes[i] <= 0\n          ? 0\n          : (slopes[i - 1] + slopes[i]) / 2,\n  );\n  return (\n    `M${points[0][0].toFixed(1)},${points[0][1].toFixed(1)}` +\n    points\n      .slice(1)\n      .map((p, i) => {\n        const prev = points[i];\n        const dx = (p[0] - prev[0]) / 3;\n        return `C${(prev[0] + dx).toFixed(1)},${(prev[1] + dx * tangents[i]).toFixed(1)} ${(p[0] - dx).toFixed(1)},${(p[1] - dx * tangents[i + 1]).toFixed(1)} ${p[0].toFixed(1)},${p[1].toFixed(1)}`;\n      })\n      .join(\"\")\n  );\n}\n\nexport function ForecastRibbonChart({\n  theme = \"dark\",\n  title = \"Revenue forecast\",\n  subtitle = \"The ribbon widens the further ahead it looks.\",\n  history = HISTORY,\n  future = FUTURE,\n  scenarios = SCENARIOS,\n  defaultScenario = 1,\n  color,\n  height = 250,\n  formatValue = FORMAT,\n  onScenarioChange,\n  className,\n  style,\n  ...props\n}: ForecastRibbonChartProps) {\n  const pal = PALETTES[theme];\n  const accent = color ?? pal.accent;\n  const reduce = useReducedMotion();\n  const boxRef = React.useRef<HTMLDivElement>(null);\n  const width = useWidth(boxRef);\n  const [index, setIndex] = React.useState(defaultScenario);\n  const [seen, setSeen] = React.useState(false);\n  const [active, setActive] = React.useState<number | null>(null);\n  const scenario = scenarios[index] ?? scenarios[0];\n  const growth = scenario?.growth ?? 0;\n  const spread = scenario?.spread ?? 0;\n  // The ribbon opens from nothing the first time it is seen, and eases between scenarios after that.\n  const [shown, setShown] = React.useState({ growth, spread: 0 });\n  const liveRef = React.useRef({ growth, spread: 0 });\n\n  React.useEffect(() => {\n    const el = boxRef.current;\n    if (!el) return;\n    const io = new IntersectionObserver(\n      ([entry]) => {\n        if (!entry.isIntersecting) return;\n        io.disconnect();\n        setSeen(true);\n      },\n      { threshold: 0.2 },\n    );\n    io.observe(el);\n    return () => io.disconnect();\n  }, []);\n\n  React.useEffect(() => {\n    if (!seen) return;\n    const from = liveRef.current;\n    let raf = 0;\n    let start = 0;\n    const frame = (now: number) => {\n      start = start || now;\n      const k = reduce ? 1 : Math.min(1, (now - start) / 650);\n      const e = 1 - Math.pow(1 - k, 3);\n      liveRef.current = {\n        growth: from.growth + (growth - from.growth) * e,\n        spread: from.spread + (spread - from.spread) * e,\n      };\n      setShown(liveRef.current);\n      if (k < 1) raf = requestAnimationFrame(frame);\n    };\n    raf = requestAnimationFrame(frame);\n    return () => cancelAnimationFrame(raf);\n  }, [seen, growth, spread, reduce]);\n\n  const count = history.length;\n  const last = history[count - 1]?.value ?? 0;\n  const steps = future.length;\n  const total = count + steps;\n  const mid = (i: number, g: number) => last * Math.pow(1 + g, i);\n  const half = (i: number, g: number, s: number, z: number) =>\n    mid(i, g) * s * Math.sqrt(i) * z;\n  // The axis fits the widest scenario, so switching never rescales the chart.\n  const top = Math.max(\n    1,\n    ...history.map((h) => h.value),\n    ...scenarios.map(\n      (c) => mid(steps, c.growth) + half(steps, c.growth, c.spread, 1.96),\n    ),\n  );\n  const lowest = Math.min(top, ...history.map((h) => h.value));\n  const tick = Math.pow(10, Math.floor(Math.log10(top))) / 2;\n  const max = Math.ceil(top / tick) * tick;\n  const floor = Math.max(0, Math.floor((lowest * 0.8) / tick) * tick);\n  const span = width - LEFT - RIGHT;\n  const base = height - BOTTOM;\n  const x = (i: number) => LEFT + (i / Math.max(1, total - 1)) * span;\n  const y = (v: number) =>\n    base - ((Math.max(floor, v) - floor) / (max - floor)) * (base - TOP);\n  const today = count - 1;\n  const ahead = Array.from({ length: steps + 1 }, (_, i) => i);\n  const line = curve(history.map((h, i) => [x(i), y(h.value)]));\n  const median = curve(\n    ahead.map((i) => [x(today + i), y(mid(i, shown.growth))]),\n  );\n  const ribbon = (z: number) => {\n    const upper = ahead.map(\n      (i) =>\n        [\n          x(today + i),\n          y(mid(i, shown.growth) + half(i, shown.growth, shown.spread, z)),\n        ] as [number, number],\n    );\n    const lower = ahead\n      .map(\n        (i) =>\n          [\n            x(today + i),\n            y(mid(i, shown.growth) - half(i, shown.growth, shown.spread, z)),\n          ] as [number, number],\n      )\n      .reverse();\n    return `${curve(upper)}L${curve(lower).slice(1)}Z`;\n  };\n  const labels = [...history.map((h) => h.label), ...future];\n  const every = Math.max(1, Math.ceil(total / Math.floor(width / 64)));\n  const end = mid(steps, shown.growth);\n  const reach = half(steps, shown.growth, shown.spread, 1.28);\n  const isFuture = active !== null && active > today;\n  const pointValue =\n    active === null\n      ? 0\n      : active > today\n        ? mid(active - today, shown.growth)\n        : (history[active]?.value ?? 0);\n\n  return (\n    <section\n      className={`w-full rounded-2xl p-5 sm:p-6 ${className ?? \"\"}`}\n      style={{\n        background: pal.card,\n        boxShadow: `inset 0 0 0 1px ${pal.border}`,\n        color: pal.text,\n        fontFamily: CARD_FONT,\n        ...style,\n      }}\n      {...props}\n    >\n      <div className=\"flex flex-wrap items-start justify-between gap-x-8 gap-y-3\">\n        <div>\n          <h3 className=\"m-0 text-[17px] leading-[1.33] font-[590] tracking-[-0.012em]\">\n            {title}\n          </h3>\n          <p\n            className=\"m-0 mt-0.5 text-[13px] tracking-[-0.011em]\"\n            style={{ color: pal.sub }}\n          >\n            {subtitle}\n          </p>\n        </div>\n        <div className=\"flex gap-7\">\n          <Stat value={formatValue(last)} label=\"Today\" pal={pal} />\n          <Stat\n            value={formatValue(end)}\n            label={`By ${future[steps - 1] ?? \"the end\"}`}\n            pal={pal}\n          />\n          <Stat\n            value={`${formatValue(end - reach)} – ${formatValue(end + reach)}`}\n            label=\"80% range\"\n            pal={pal}\n          />\n        </div>\n      </div>\n\n      {!count || !steps ? (\n        <p className=\"py-16 text-center text-sm\" style={{ color: pal.sub }}>\n          No data available.\n        </p>\n      ) : (\n        <div\n          ref={boxRef}\n          className=\"relative mt-5 rounded-lg outline-none focus-visible:ring-2\"\n          tabIndex={0}\n          role=\"group\"\n          aria-label={`${title}. Use left and right arrow keys to read each month.`}\n          onPointerMove={(e) => {\n            const r = e.currentTarget.getBoundingClientRect();\n            const i = Math.round(\n              ((e.clientX - r.left - LEFT) / span) * (total - 1),\n            );\n            setActive(Math.max(0, Math.min(total - 1, i)));\n          }}\n          onPointerLeave={() => setActive(null)}\n          onBlur={() => setActive(null)}\n          onKeyDown={(e) => {\n            if (e.key !== \"ArrowLeft\" && e.key !== \"ArrowRight\") return;\n            e.preventDefault();\n            const dir = e.key === \"ArrowRight\" ? 1 : -1;\n            setActive((a) =>\n              Math.max(0, Math.min(total - 1, (a ?? today) + dir)),\n            );\n          }}\n        >\n          <svg\n            viewBox={`0 0 ${width} ${height}`}\n            className=\"block w-full\"\n            style={{ height }}\n            role=\"img\"\n            aria-label={`${scenario?.label} scenario: ${formatValue(end)} by ${future[steps - 1]}, likely between ${formatValue(end - reach)} and ${formatValue(end + reach)}`}\n          >\n            {[0, 0.25, 0.5, 0.75, 1].map((t) => (\n              <g key={t}>\n                <line\n                  x1={LEFT}\n                  x2={width - RIGHT}\n                  y1={y(floor + (max - floor) * t)}\n                  y2={y(floor + (max - floor) * t)}\n                  stroke={pal.grid}\n                />\n                <text\n                  x={LEFT - 8}\n                  y={y(floor + (max - floor) * t) + 4}\n                  textAnchor=\"end\"\n                  fontSize=\"11\"\n                  fill={pal.faint}\n                >\n                  {formatValue(floor + (max - floor) * t)}\n                </text>\n              </g>\n            ))}\n            {labels.map(\n              (label, i) =>\n                i % every === 0 && (\n                  <text\n                    key={i}\n                    x={x(i)}\n                    y={height - 6}\n                    textAnchor={i === 0 ? \"start\" : \"middle\"}\n                    fontSize=\"11\"\n                    fill={pal.faint}\n                  >\n                    {label}\n                  </text>\n                ),\n            )}\n            {BANDS.map((b) => (\n              <path\n                key={b.name}\n                d={ribbon(b.z)}\n                fill={accent}\n                fillOpacity={b.opacity}\n              />\n            ))}\n            <line\n              x1={x(today)}\n              x2={x(today)}\n              y1={TOP}\n              y2={base}\n              stroke={pal.border}\n            />\n            <text x={x(today) + 6} y={TOP + 10} fontSize=\"11\" fill={pal.faint}>\n              Forecast\n            </text>\n            <path\n              d={line}\n              fill=\"none\"\n              stroke={pal.soft}\n              strokeWidth=\"1.75\"\n              strokeLinecap=\"round\"\n            />\n            <path\n              d={median}\n              fill=\"none\"\n              stroke={accent}\n              strokeWidth=\"2\"\n              strokeLinecap=\"round\"\n            />\n            <circle\n              cx={x(today)}\n              cy={y(last)}\n              r=\"3.5\"\n              fill={pal.soft}\n              stroke={pal.card}\n              strokeWidth=\"2\"\n            />\n            {active !== null && (\n              <g>\n                <line\n                  x1={x(active)}\n                  x2={x(active)}\n                  y1={TOP}\n                  y2={base}\n                  stroke={pal.border}\n                />\n                <circle\n                  cx={x(active)}\n                  cy={y(pointValue)}\n                  r=\"3.5\"\n                  fill={isFuture ? accent : pal.soft}\n                  stroke={pal.card}\n                  strokeWidth=\"2\"\n                />\n              </g>\n            )}\n          </svg>\n\n          {active !== null && (\n            <Tip x={x(active)} y={y(pointValue)} width={width} pal={pal}>\n              <span className=\"font-[510]\" style={{ color: pal.text }}>\n                {formatValue(pointValue)}\n              </span>{\" \"}\n              in {labels[active]}\n              {isFuture &&\n                `, ${formatValue(pointValue - half(active - today, shown.growth, shown.spread, 1.28))} to ${formatValue(pointValue + half(active - today, shown.growth, shown.spread, 1.28))}`}\n            </Tip>\n          )}\n        </div>\n      )}\n\n      <div className=\"mt-3 flex flex-wrap items-center justify-between gap-2\">\n        <Pills\n          label=\"Scenario\"\n          options={scenarios.map((c) => c.label)}\n          value={index}\n          onChange={(i) => {\n            setIndex(i);\n            onScenarioChange?.(scenarios[i]);\n          }}\n          pal={pal}\n        />\n        <div\n          className=\"flex items-center gap-3 text-[12px]\"\n          style={{ color: pal.sub }}\n        >\n          {[...BANDS].reverse().map((b) => (\n            <span key={b.name} className=\"flex items-center gap-1.5\">\n              <span\n                className=\"h-2.5 w-3.5 rounded-[3px]\"\n                style={{\n                  background: accent,\n                  opacity: b.opacity * 2,\n                }}\n              />\n              {b.name}\n            </span>\n          ))}\n        </div>\n      </div>\n    </section>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}