{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ab-test-result-card",
  "title": "A/B Test Result Card",
  "description": "An experiment result worked out from your raw counts: rates, change, confidence and a 95% interval for each metric, with a daily chart and a clear ship or keep running call.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/new-york/ab-test-result-card/ab-test-result-card.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nexport interface AbTestArm {\n  visitors: number;\n  conversions: number;\n}\n\nexport interface AbTestMetric {\n  id: string;\n  label: string;\n  control: AbTestArm;\n  variant: AbTestArm;\n  /** Running rate per day, in percent. Both lists should be the same length. */\n  controlSeries: number[];\n  variantSeries: number[];\n}\n\nexport interface AbTestResultCardProps extends Omit<\n  React.ComponentPropsWithoutRef<\"section\">,\n  \"title\"\n> {\n  theme?: \"dark\" | \"light\";\n  title?: string;\n  hypothesis?: string;\n  controlName?: string;\n  variantName?: string;\n  metrics?: AbTestMetric[];\n  /** The confidence a result needs before it counts, in percent. */\n  target?: number;\n  /** Visitors the test planned for. */\n  sampleGoal?: number;\n  onShip?: (metric: AbTestMetric) => void;\n}\n\nconst FONT =\n  '\"Inter Variable\", Inter, \"SF Pro Display\", -apple-system, BlinkMacSystemFont, sans-serif';\nconst ACCENT = \"#5E6AD2\";\nconst GREEN = \"#27A644\";\nconst RED = \"#EB5757\";\n\nconst PALETTES = {\n  dark: {\n    card: \"#0F1011\",\n    inset: \"#161718\",\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    control: \"#8A8F98\",\n    chip: \"rgba(255,255,255,0.05)\",\n    tab: \"rgba(255,255,255,0.08)\",\n    btn: \"#E5E5E6\",\n    btnText: \"#08090A\",\n  },\n  light: {\n    card: \"#FFFFFF\",\n    inset: \"#F7F8F8\",\n    border: \"rgba(8,9,10,0.1)\",\n    grid: \"rgba(8,9,10,0.06)\",\n    text: \"#08090A\",\n    soft: \"#3C3F44\",\n    sub: \"#62666D\",\n    faint: \"#8A8F98\",\n    control: \"#8A8F98\",\n    chip: \"rgba(8,9,10,0.05)\",\n    tab: \"#FFFFFF\",\n    btn: \"#08090A\",\n    btnText: \"#F7F8F8\",\n  },\n};\n\nconst DEFAULT_METRICS: AbTestMetric[] = [\n  {\n    id: \"purchase\",\n    label: \"Purchase\",\n    control: { visitors: 19240, conversions: 793 },\n    variant: { visitors: 19180, conversions: 934 },\n    controlSeries: [3.6, 4.4, 3.9, 4.3, 4.0, 4.2, 4.1, 4.2, 4.1, 4.1, 4.12, 4.12],\n    variantSeries: [4.1, 4.3, 4.6, 4.5, 4.8, 4.7, 4.9, 4.8, 4.9, 4.85, 4.88, 4.87],\n  },\n  {\n    id: \"cart\",\n    label: \"Add to cart\",\n    control: { visitors: 19240, conversions: 3210 },\n    variant: { visitors: 19180, conversions: 3296 },\n    controlSeries: [15.8, 17.2, 16.1, 16.9, 16.4, 16.8, 16.6, 16.7, 16.6, 16.7, 16.7, 16.68],\n    variantSeries: [17.4, 16.3, 17.6, 16.8, 17.5, 17.0, 17.3, 17.1, 17.2, 17.2, 17.2, 17.18],\n  },\n  {\n    id: \"return\",\n    label: \"Came back\",\n    control: { visitors: 793, conversions: 412 },\n    variant: { visitors: 934, conversions: 478 },\n    controlSeries: [48, 55, 50, 54, 51, 53, 52, 52.5, 51.8, 52.2, 52, 51.95],\n    variantSeries: [54, 49, 53, 50, 52.5, 50.5, 51.8, 51, 51.5, 51.1, 51.3, 51.18],\n  },\n];\n\n/** Drawn as SVG, because a tiny border-radius circle turns lumpy on 1x screens and fractional positions. */\nfunction Dot({ size, color }: { size: number; color: string }) {\n  const r = size / 2;\n  return (\n    <svg\n      aria-hidden=\"true\"\n      width={size}\n      height={size}\n      viewBox={`0 0 ${size} ${size}`}\n      className=\"block shrink-0\"\n    >\n      <circle\n        cx={r}\n        cy={r}\n        r={r}\n        className=\"motion-safe:transition-[fill] motion-safe:duration-200\"\n        style={{ fill: color }}\n      />\n    </svg>\n  );\n}\n\n/** Normal CDF, from the Abramowitz and Stegun approximation of erf. */\nfunction normalCdf(z: number) {\n  const x = Math.abs(z) / Math.SQRT2;\n  const t = 1 / (1 + 0.3275911 * x);\n  const poly =\n    t *\n    (0.254829592 +\n      t * (-0.284496736 + t * (1.421413741 + t * (-1.453152027 + t * 1.061405429))));\n  const erf = 1 - poly * Math.exp(-x * x);\n  return z >= 0 ? 0.5 * (1 + erf) : 0.5 * (1 - erf);\n}\n\nconst round = (n: number, places = 2) => {\n  const f = 10 ** places;\n  return Math.round(n * f) / f;\n};\n\n/** A two-sided, two-proportion z-test, with the 95% interval as a change on the control. */\nfunction analyse(metric: AbTestMetric) {\n  const { control, variant } = metric;\n  const a = control.conversions / control.visitors;\n  const b = variant.conversions / variant.visitors;\n  const pooled =\n    (control.conversions + variant.conversions) /\n    (control.visitors + variant.visitors);\n  const pooledSe = Math.sqrt(\n    pooled * (1 - pooled) * (1 / control.visitors + 1 / variant.visitors),\n  );\n  const se = Math.sqrt(\n    (a * (1 - a)) / control.visitors + (b * (1 - b)) / variant.visitors,\n  );\n  const z = pooledSe ? (b - a) / pooledSe : 0;\n  const confidence = (2 * normalCdf(Math.abs(z)) - 1) * 100;\n  return {\n    controlRate: round(a * 100),\n    variantRate: round(b * 100),\n    uplift: round(((b - a) / a) * 100, 1),\n    low: round(((b - a - 1.96 * se) / a) * 100, 1),\n    high: round(((b - a + 1.96 * se) / a) * 100, 1),\n    confidence: round(Math.min(confidence, 99.9), 1),\n  };\n}\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/** Eases a list of numbers to new values, so one switch moves every figure and line together. */\nfunction useTween(target: number[], ms: number, off: boolean) {\n  const [shown, setShown] = React.useState(target);\n  const from = React.useRef(target);\n  const key = target.join(\",\");\n  React.useEffect(() => {\n    const goal = key.split(\",\").map(Number);\n    const start = from.current;\n    if (off || start.length !== goal.length) {\n      from.current = goal;\n      const id = requestAnimationFrame(() => setShown(goal));\n      return () => cancelAnimationFrame(id);\n    }\n    let raf = 0;\n    const began = performance.now();\n    const tick = (now: number) => {\n      const p = Math.min(1, (now - began) / ms);\n      const e = 1 - (1 - p) ** 3;\n      const next = goal.map((g, i) => start[i] + (g - start[i]) * e);\n      from.current = next;\n      setShown(next);\n      if (p < 1) raf = requestAnimationFrame(tick);\n    };\n    raf = requestAnimationFrame(tick);\n    return () => cancelAnimationFrame(raf);\n  }, [key, ms, off]);\n  return shown;\n}\n\nfunction useWidth<T extends HTMLElement>(fallback: number) {\n  const ref = React.useRef<T>(null);\n  const [width, setWidth] = React.useState(fallback);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) => {\n      setWidth(Math.round(entry.contentRect.width));\n    });\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, []);\n  return [ref, width] as const;\n}\n\nconst signed = (n: number, places = 1) =>\n  `${n >= 0 ? \"+\" : \"−\"}${Math.abs(n).toFixed(places)}%`;\n\nexport function AbTestResultCard({\n  theme = \"dark\",\n  title = \"Shorter checkout\",\n  hypothesis = \"One page instead of three should lift completed orders.\",\n  controlName = \"Three steps\",\n  variantName = \"One page\",\n  metrics = DEFAULT_METRICS,\n  target = 95,\n  sampleGoal = 50000,\n  onShip,\n  className,\n  style,\n  ...rest\n}: AbTestResultCardProps) {\n  const c = PALETTES[theme];\n  const reduce = useReducedMotion();\n  const [index, setIndex] = React.useState(0);\n  const [hover, setHover] = React.useState<number | null>(null);\n  const [chartRef, width] = useWidth<HTMLDivElement>(620);\n  const metric = metrics[index] ?? metrics[0];\n  const stats = React.useMemo(() => analyse(metric), [metric]);\n  const days = metric.controlSeries.length;\n\n  const values = useTween(\n    [\n      stats.controlRate,\n      stats.variantRate,\n      stats.uplift,\n      stats.confidence,\n      stats.low,\n      stats.high,\n      ...metric.controlSeries,\n      ...metric.variantSeries,\n    ],\n    420,\n    reduce,\n  );\n  const [controlRate, variantRate, uplift, confidence, low, high] = values;\n  const controlLine = values.slice(6, 6 + days);\n  const variantLine = values.slice(6 + days);\n\n  const winner = stats.confidence >= target;\n  const verdict = !winner\n    ? { label: \"Not conclusive yet\", dot: c.faint }\n    : stats.uplift > 0\n      ? { label: `${variantName} wins`, dot: GREEN }\n      : { label: `${controlName} wins`, dot: RED };\n  const canShip = winner && stats.uplift > 0;\n\n  // The chart. Drawn at its measured width, so nothing stretches on a phone.\n  const H = 148;\n  const left = 38;\n  const top = 8;\n  const bottom = H - 20;\n  const all = [...controlLine, ...variantLine];\n  const lo = Math.min(...all);\n  const hi = Math.max(...all);\n  const pad = (hi - lo) * 0.14 || 1;\n  const yMin = lo - pad;\n  const yMax = hi + pad;\n  const x = (i: number) => round(left + (i / (days - 1)) * (width - left - 4), 1);\n  const y = (v: number) =>\n    round(bottom - ((v - yMin) / (yMax - yMin)) * (bottom - top), 1);\n  const toPath = (line: number[]) =>\n    line.map((v, i) => `${i ? \"L\" : \"M\"}${x(i)} ${y(v)}`).join(\" \");\n  const ticks = [yMax, (yMax + yMin) / 2, yMin];\n\n  const pointAt = (clientX: number, el: HTMLElement) => {\n    const box = el.getBoundingClientRect();\n    const ratio = (clientX - box.left - left) / (box.width - left - 4);\n    return Math.max(0, Math.min(days - 1, Math.round(ratio * (days - 1))));\n  };\n\n  // The interval strip. Zero stays in the middle, so a bar that crosses it reads as no clear change.\n  const reach = Math.max(\n    Math.abs(stats.low),\n    Math.abs(stats.high),\n    ...metrics.flatMap((m) => {\n      const s = analyse(m);\n      return [Math.abs(s.low), Math.abs(s.high)];\n    }),\n    1,\n  );\n  const at = (n: number) => round(50 + (n / reach) * 46, 2);\n\n  const seen = metrics[0].control.visitors + metrics[0].variant.visitors;\n  const progress = Math.min(100, round((seen / sampleGoal) * 100, 1));\n\n  return (\n    <section\n      aria-label={title}\n      className={`@container w-full rounded-2xl border ${className ?? \"\"}`}\n      style={{\n        background: c.card,\n        borderColor: c.border,\n        color: c.text,\n        fontFamily: FONT,\n        ...style,\n      }}\n      {...rest}\n    >\n      <header className=\"flex flex-wrap items-start justify-between gap-x-4 gap-y-2 p-5 pb-4 @xl:p-6 @xl:pb-4\">\n        <div className=\"min-w-0 flex-1 basis-[240px]\">\n          <h3 className=\"m-0 text-[20px] leading-[26px] font-[590] tracking-[-0.018em]\">\n            {title}\n          </h3>\n          <p\n            className=\"m-0 mt-1 text-[13px] leading-[20px] tracking-[-0.011em]\"\n            style={{ color: c.sub }}\n          >\n            {hypothesis}\n          </p>\n        </div>\n        <p\n          aria-live=\"polite\"\n          className=\"m-0 flex h-7 shrink-0 items-center gap-2 rounded-full px-3 text-[12.5px] font-[510] tracking-[-0.011em]\"\n          style={{ background: c.chip, color: c.soft }}\n        >\n          <Dot size={6} color={verdict.dot} />\n          {verdict.label}\n        </p>\n      </header>\n\n      <div className=\"px-5 @xl:px-6\">\n        <div\n          role=\"group\"\n          aria-label=\"Metric\"\n          className=\"relative grid h-8 rounded-full p-0.5\"\n          style={{\n            background: c.chip,\n            gridTemplateColumns: `repeat(${metrics.length}, minmax(0, 1fr))`,\n          }}\n        >\n          <span\n            aria-hidden=\"true\"\n            className=\"absolute top-0.5 bottom-0.5 left-0.5 rounded-full motion-safe:transition-transform motion-safe:duration-300\"\n            style={{\n              width: `calc((100% - 4px) / ${metrics.length})`,\n              transform: `translateX(${index * 100}%)`,\n              background: c.tab,\n            }}\n          />\n          {metrics.map((m, i) => (\n            <button\n              key={m.id}\n              type=\"button\"\n              aria-pressed={i === index}\n              onClick={() => {\n                setIndex(i);\n                setHover(null);\n              }}\n              className=\"relative cursor-pointer truncate rounded-full border-0 bg-transparent px-2 text-[12.5px] font-[510] tracking-[-0.011em] outline-none focus-visible:ring-2 focus-visible:ring-[#5E6AD2] motion-safe:transition-colors motion-safe:duration-200\"\n              style={{ color: i === index ? c.text : c.sub }}\n            >\n              {m.label}\n            </button>\n          ))}\n        </div>\n\n        <dl className=\"m-0 mt-4 grid grid-cols-2 gap-x-4 gap-y-3 @xl:grid-cols-4\">\n          {[\n            { label: controlName, value: `${controlRate.toFixed(2)}%`, dot: c.control },\n            { label: variantName, value: `${variantRate.toFixed(2)}%`, dot: ACCENT },\n            { label: \"Change\", value: signed(uplift) },\n            { label: \"Confidence\", value: `${confidence.toFixed(1)}%` },\n          ].map((s) => (\n            <div key={s.label} className=\"min-w-0\">\n              <dt\n                className=\"flex items-center gap-1.5 text-[12px] leading-[16px] tracking-[-0.005em]\"\n                style={{ color: c.sub }}\n              >\n                {s.dot && (\n                  <Dot size={6} color={s.dot} />\n                )}\n                <span className=\"truncate\">{s.label}</span>\n              </dt>\n              <dd className=\"m-0 mt-1 text-[22px] leading-[28px] font-[510] tracking-[-0.022em] tabular-nums\">\n                {s.value}\n              </dd>\n            </div>\n          ))}\n        </dl>\n\n        <p\n          className=\"m-0 mt-3 h-4 text-[12px] leading-[16px] tracking-[-0.005em] tabular-nums\"\n          style={{ color: c.sub }}\n        >\n          {hover === null\n            ? \"Daily running rate\"\n            : `Day ${hover + 1}: ${controlName} ${controlLine[hover].toFixed(2)}%, ${variantName} ${variantLine[hover].toFixed(2)}%`}\n        </p>\n        <div\n          ref={chartRef}\n          role=\"img\"\n          aria-label={`${metric.label}: ${controlName} ${stats.controlRate}%, ${variantName} ${stats.variantRate}%, ${stats.confidence}% confidence.`}\n          className=\"mt-1 w-full touch-pan-y\"\n          style={{ height: H }}\n          onPointerMove={(e) => setHover(pointAt(e.clientX, e.currentTarget))}\n          onPointerLeave={() => setHover(null)}\n        >\n          <svg aria-hidden=\"true\" width={width} height={H} className=\"block\">\n            {ticks.map((t, i) => (\n              <g key={i}>\n                <line\n                  x1={left}\n                  x2={width - 4}\n                  y1={y(t)}\n                  y2={y(t)}\n                  stroke={c.grid}\n                />\n                <text\n                  x={0}\n                  y={y(t) + 4}\n                  fontSize=\"11\"\n                  fill={c.faint}\n                  style={{ fontVariantNumeric: \"tabular-nums\" }}\n                >\n                  {t.toFixed(t >= 10 ? 1 : 2)}\n                </text>\n              </g>\n            ))}\n            {hover !== null && (\n              <line\n                x1={x(hover)}\n                x2={x(hover)}\n                y1={top}\n                y2={bottom}\n                stroke={c.faint}\n              />\n            )}\n            <path\n              d={toPath(controlLine)}\n              fill=\"none\"\n              stroke={c.control}\n              strokeWidth=\"1.5\"\n              strokeLinejoin=\"round\"\n            />\n            <path\n              d={toPath(variantLine)}\n              fill=\"none\"\n              stroke={ACCENT}\n              strokeWidth=\"2\"\n              strokeLinejoin=\"round\"\n            />\n            {hover !== null && (\n              <>\n                <circle cx={x(hover)} cy={y(controlLine[hover])} r=\"3\" fill={c.control} />\n                <circle cx={x(hover)} cy={y(variantLine[hover])} r=\"3.5\" fill={ACCENT} />\n              </>\n            )}\n            <text x={left} y={H - 4} fontSize=\"11\" fill={c.faint}>\n              Day 1\n            </text>\n            <text x={width - 4} y={H - 4} fontSize=\"11\" fill={c.faint} textAnchor=\"end\">\n              Day {days}\n            </text>\n          </svg>\n        </div>\n\n        <div className=\"mt-3\">\n          <div\n            className=\"flex items-center justify-between text-[12px] leading-[16px] tracking-[-0.005em] tabular-nums\"\n            style={{ color: c.sub }}\n          >\n            <span>95% interval</span>\n            <span>\n              {signed(low)} to {signed(high)}\n            </span>\n          </div>\n          <div aria-hidden=\"true\" className=\"relative mt-2 h-3\">\n            <span\n              className=\"absolute inset-x-0 top-1/2 h-px\"\n              style={{ background: c.border }}\n            />\n            <span\n              className=\"absolute top-0 bottom-0 w-px\"\n              style={{ left: \"50%\", background: c.faint }}\n            />\n            <span\n              className=\"absolute top-1/2 h-1 -translate-y-1/2 rounded-full\"\n              style={{\n                left: `${at(low)}%`,\n                width: `${Math.max(0, at(high) - at(low))}%`,\n                background: canShip ? ACCENT : c.control,\n              }}\n            />\n            <span\n              className=\"absolute top-1/2 size-2.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2\"\n              style={{\n                left: `${at(uplift)}%`,\n                background: c.card,\n                borderColor: canShip ? ACCENT : c.control,\n              }}\n            />\n          </div>\n        </div>\n      </div>\n\n      <footer\n        className=\"mt-4 flex items-center justify-between gap-4 border-t px-5 py-3.5 @xl:px-6\"\n        style={{ borderColor: c.border }}\n      >\n        <div className=\"min-w-0 flex-1\">\n          <p\n            className=\"m-0 truncate text-[12px] leading-[16px] tracking-[-0.005em] tabular-nums\"\n            style={{ color: c.sub }}\n          >\n            {seen.toLocaleString(\"en-US\")} of {sampleGoal.toLocaleString(\"en-US\")} visitors\n          </p>\n          <div\n            aria-hidden=\"true\"\n            className=\"mt-1.5 h-1 max-w-[220px] overflow-hidden rounded-full\"\n            style={{ background: c.chip }}\n          >\n            <div\n              className=\"h-full rounded-full\"\n              style={{ width: `${progress}%`, background: c.control }}\n            />\n          </div>\n        </div>\n        <button\n          type=\"button\"\n          disabled={!canShip}\n          onClick={() => onShip?.(metric)}\n          className=\"h-9 w-[124px] shrink-0 cursor-pointer rounded-full border-0 text-[13px] font-[510] tracking-[-0.011em] outline-none focus-visible:ring-2 focus-visible:ring-[#5E6AD2] focus-visible:ring-offset-2 disabled:cursor-default motion-safe:transition-colors motion-safe:duration-200\"\n          style={{\n            background: canShip ? c.btn : c.chip,\n            color: canShip ? c.btnText : c.sub,\n          }}\n        >\n          {canShip ? \"Ship variant\" : \"Keep running\"}\n        </button>\n      </footer>\n    </section>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}