{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"kpi-counter","type":"registry:block","title":"KPI counter","description":"A row of KPI cards whose numbers spring into view, with delta badges and self-drawing sparklines.","dependencies":["motion","lucide-react"],"registryDependencies":["utils"],"files":[{"path":"registry/prequel/kpi-counter/kpi-counter.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport {\n  MotionConfig,\n  animate,\n  motion,\n  useInView,\n  useReducedMotion,\n} from \"motion/react\";\nimport { ArrowDownRight, ArrowUpRight } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\n\nconst EASE: [number, number, number, number] = [0.22, 1, 0.36, 1];\n\n/* ------------------------------------------------------------------ */\n/* types                                                               */\n/* ------------------------------------------------------------------ */\n\nexport type KpiCounterItem = {\n  id: string;\n  label: string;\n  value: number;\n  prefix?: string;\n  suffix?: string;\n  decimals?: number;\n  /** Signed change vs the previous period, e.g. 12.4 for +12.4%. */\n  delta: number;\n  /** Unit shown after the delta value, e.g. \"%\" or \" pts\". Defaults to \"%\". */\n  deltaSuffix?: string;\n  /** Decimals shown on the delta value. Defaults to 1. */\n  deltaDecimals?: number;\n  /** Short context after the badge, e.g. \"vs last month\". */\n  deltaLabel?: string;\n  /** When true a negative delta is good (e.g. churn going down). */\n  goodWhenDown?: boolean;\n  /** Sparkline values, drawn left to right. */\n  sparkline: number[];\n  /** Chart colour token 1–5. Defaults to 1. */\n  tone?: number;\n};\n\nexport type KpiCounterProps = {\n  className?: string;\n  items?: KpiCounterItem[];\n  formatValue?: (value: number, item: KpiCounterItem) => string;\n};\n\n/* ------------------------------------------------------------------ */\n/* deterministic demo data (no Math.random / Date.now at module load)  */\n/* ------------------------------------------------------------------ */\n\nconst DEFAULT_ITEMS: KpiCounterItem[] = [\n  {\n    id: \"mrr\",\n    label: \"Monthly recurring revenue\",\n    value: 84260,\n    prefix: \"$\",\n    decimals: 0,\n    delta: 12.4,\n    deltaLabel: \"vs last month\",\n    sparkline: [61, 63, 62, 65, 67, 71, 70, 74, 77, 80, 82, 84],\n    tone: 1,\n  },\n  {\n    id: \"users\",\n    label: \"Active users\",\n    value: 12480,\n    decimals: 0,\n    delta: 8.2,\n    deltaLabel: \"vs last month\",\n    sparkline: [8.2, 8.5, 8.4, 8.9, 9.1, 9.6, 9.8, 10.3, 10.9, 11.5, 12.1, 12.48],\n    tone: 2,\n  },\n  {\n    id: \"churn\",\n    label: \"Revenue churn\",\n    value: 1.9,\n    suffix: \"%\",\n    decimals: 1,\n    delta: -0.4,\n    deltaSuffix: \" pts\",\n    deltaDecimals: 1,\n    deltaLabel: \"lower is better\",\n    goodWhenDown: true,\n    sparkline: [2.9, 2.8, 2.9, 2.6, 2.5, 2.4, 2.5, 2.2, 2.1, 2.0, 1.95, 1.9],\n    tone: 3,\n  },\n  {\n    id: \"arpu\",\n    label: \"Avg. revenue per account\",\n    value: 68.4,\n    prefix: \"$\",\n    decimals: 2,\n    delta: 4.2,\n    deltaLabel: \"vs last month\",\n    sparkline: [59.4, 60.1, 60.0, 61.3, 62.1, 63.0, 63.8, 64.5, 65.2, 66.1, 67.3, 68.4],\n    tone: 4,\n  },\n];\n\n/* ------------------------------------------------------------------ */\n/* helpers                                                             */\n/* ------------------------------------------------------------------ */\n\nfunction defaultFormat(value: number, item: KpiCounterItem) {\n  const decimals = item.decimals ?? 0;\n  const number = value.toLocaleString(\"en-US\", {\n    minimumFractionDigits: decimals,\n    maximumFractionDigits: decimals,\n  });\n  return `${item.prefix ?? \"\"}${number}${item.suffix ?? \"\"}`;\n}\n\nfunction formatDelta(item: KpiCounterItem) {\n  const decimals = item.deltaDecimals ?? 1;\n  const sign = item.delta >= 0 ? \"+\" : \"−\";\n  return `${sign}${Math.abs(item.delta).toFixed(decimals)}${item.deltaSuffix ?? \"%\"}`;\n}\n\ntype Pt = { x: number; y: number };\n\nfunction sparklinePoints(\n  values: number[],\n  w: number,\n  h: number,\n  pad: number\n): Pt[] {\n  const n = values.length;\n  if (n === 1) return [{ x: pad, y: h - pad }];\n  const min = Math.min(...values);\n  const max = Math.max(...values);\n  const range = max - min || 1;\n  return values.map((v, i) => ({\n    x: pad + ((w - pad * 2) * i) / (n - 1),\n    y: h - pad - ((v - min) / range) * (h - pad * 2),\n  }));\n}\n\nfunction sparkPath(values: number[], w: number, h: number, pad: number) {\n  const pts = sparklinePoints(values, w, h, pad);\n  return pts\n    .map((p, i) => {\n      if (i === 0) return `M${p.x},${p.y}`;\n      const q = pts[i - 1];\n      const cx = (q.x + p.x) / 2;\n      return `C${cx},${q.y} ${cx},${p.y} ${p.x},${p.y}`;\n    })\n    .join(\" \");\n}\n\n/* ------------------------------------------------------------------ */\n/* count-up with a spring                                              */\n/* ------------------------------------------------------------------ */\n\nfunction useCountUp(\n  target: number,\n  opts: { start: boolean; reduce: boolean; delay: number }\n) {\n  const [value, setValue] = useState(target);\n  const started = useRef(false);\n\n  useEffect(() => {\n    if (!opts.start) return;\n    if (opts.reduce) {\n      setValue(target);\n      return;\n    }\n    if (started.current) return;\n    started.current = true;\n\n    const controls = animate(0, target, {\n      type: \"spring\",\n      stiffness: 100,\n      damping: 16,\n      delay: opts.delay,\n      onUpdate: (v) => setValue(v),\n      onComplete: () => setValue(target),\n    });\n\n    return () => controls.stop();\n  }, [opts.start, target, opts.reduce, opts.delay]);\n\n  return value;\n}\n\n/* ------------------------------------------------------------------ */\n/* sparkline                                                          */\n/* ------------------------------------------------------------------ */\n\nconst SPARK_W = 72;\nconst SPARK_H = 32;\nconst SPARK_PAD = 7;\n\ntype SparklineProps = {\n  values: number[];\n  color: string;\n  draw: boolean;\n  hovered: boolean;\n  reduce: boolean;\n  delay: number;\n  label: string;\n  className?: string;\n};\n\nfunction Sparkline({\n  values,\n  color,\n  draw,\n  hovered,\n  reduce,\n  delay,\n  label,\n  className,\n}: SparklineProps) {\n  const d = sparkPath(values, SPARK_W, SPARK_H, SPARK_PAD);\n  const last = sparklinePoints(values, SPARK_W, SPARK_H, SPARK_PAD)[\n    values.length - 1\n  ];\n\n  return (\n    <svg\n      viewBox={`0 0 ${SPARK_W} ${SPARK_H}`}\n      className={cn(\"h-8 w-[72px] shrink-0\", className)}\n      role=\"img\"\n      aria-label={label}\n    >\n      <motion.path\n        d={d}\n        fill=\"none\"\n        stroke={color}\n        strokeWidth={1.5}\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        initial={{ pathLength: 0 }}\n        animate={{ pathLength: draw ? 1 : 0 }}\n        transition={reduce ? { duration: 0 } : { duration: 0.9, ease: EASE, delay }}\n      />\n\n      {/* last point: a lens that lights up on hover */}\n      <motion.g\n        initial={false}\n        animate={{ opacity: hovered ? 1 : 0 }}\n        transition={{ duration: 0.2 }}\n      >\n        <circle\n          cx={last.x}\n          cy={last.y}\n          r={5}\n          fill=\"none\"\n          stroke={color}\n          strokeWidth={1}\n          opacity={0.4}\n        />\n        <circle\n          cx={last.x}\n          cy={last.y}\n          r={2.25}\n          fill=\"var(--card)\"\n          stroke={color}\n          strokeWidth={1.5}\n        />\n      </motion.g>\n\n      {/* the glint dot rides the rim of the lens */}\n      <motion.g\n        initial={false}\n        animate={{ opacity: hovered ? 1 : 0, rotate: hovered ? 45 : -120 }}\n        transition={{\n          opacity: { duration: 0.2 },\n          rotate: { type: \"spring\", stiffness: 140, damping: 16 },\n        }}\n        style={{ transformOrigin: `${last.x}px ${last.y}px` }}\n      >\n        <circle cx={last.x} cy={last.y - 5} r={1.5} fill={color} />\n      </motion.g>\n    </svg>\n  );\n}\n\n/* ------------------------------------------------------------------ */\n/* card                                                               */\n/* ------------------------------------------------------------------ */\n\ntype KpiCardProps = {\n  item: KpiCounterItem;\n  index: number;\n  show: boolean;\n  reduce: boolean;\n  format: (value: number, item: KpiCounterItem) => string;\n};\n\nfunction KpiCard({ item, index, show, reduce, format }: KpiCardProps) {\n  const [hovered, setHovered] = useState(false);\n  const value = useCountUp(item.value, {\n    start: show,\n    reduce,\n    delay: index * 0.06,\n  });\n\n  const tone = item.tone ?? 1;\n  const color = `var(--chart-${tone})`;\n\n  const positive = item.delta > 0;\n  const neutral = item.delta === 0;\n  const good = item.goodWhenDown ? item.delta < 0 : item.delta > 0;\n\n  return (\n    <motion.div\n      initial={{ opacity: 0, y: reduce ? 0 : 16 }}\n      animate={{ opacity: show ? 1 : 0, y: 0 }}\n      transition={{\n        duration: reduce ? 0 : 0.55,\n        delay: reduce ? 0 : index * 0.06,\n        ease: EASE,\n      }}\n      onPointerEnter={() => setHovered(true)}\n      onPointerLeave={() => setHovered(false)}\n      className=\"flex flex-col gap-3 rounded-xl border border-border bg-card p-5 text-card-foreground shadow-sm transition-colors hover:border-muted-foreground/30\"\n    >\n      <span className=\"truncate text-[13px] font-medium text-muted-foreground\">\n        {item.label}\n      </span>\n\n      <div className=\"flex flex-wrap items-end justify-between gap-x-3 gap-y-2\">\n        <span className=\"min-w-0 text-[28px] font-semibold leading-none tracking-tight tabular-nums\">\n          {format(value, item)}\n        </span>\n        <Sparkline\n          values={item.sparkline}\n          color={color}\n          draw={show}\n          hovered={hovered}\n          reduce={reduce}\n          delay={0.1 + index * 0.08}\n          label={`${item.label} trend, ${item.sparkline.length} points`}\n        />\n      </div>\n\n      <div className=\"flex flex-wrap items-center gap-2\">\n        <span\n          className={cn(\n            \"inline-flex items-center gap-0.5 rounded-full px-1.5 py-0.5 text-[11px] font-medium tabular-nums\",\n            neutral\n              ? \"bg-muted text-muted-foreground\"\n              : good\n                ? \"bg-success/10 text-success\"\n                : \"bg-destructive/10 text-destructive\"\n          )}\n        >\n          {neutral ? null : positive ? (\n            <ArrowUpRight className=\"h-3 w-3\" />\n          ) : (\n            <ArrowDownRight className=\"h-3 w-3\" />\n          )}\n          {formatDelta(item)}\n        </span>\n        {item.deltaLabel ? (\n          <span className=\"truncate text-[12.5px] text-muted-foreground\">\n            {item.deltaLabel}\n          </span>\n        ) : null}\n      </div>\n    </motion.div>\n  );\n}\n\n/* ------------------------------------------------------------------ */\n/* block                                                              */\n/* ------------------------------------------------------------------ */\n\nexport function KpiCounter({\n  className,\n  items = DEFAULT_ITEMS,\n  formatValue,\n}: KpiCounterProps) {\n  const ref = useRef<HTMLDivElement>(null);\n  const inView = useInView(ref, { once: true, margin: \"-10% 0px\" });\n  const reduce = Boolean(useReducedMotion());\n  const show = inView;\n  const format = formatValue ?? defaultFormat;\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <div\n        ref={ref}\n        className={cn(\n          \"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4\",\n          className\n        )}\n      >\n        {items.map((item, index) => (\n          <KpiCard\n            key={item.id}\n            item={item}\n            index={index}\n            show={show}\n            reduce={reduce}\n            format={format}\n          />\n        ))}\n      </div>\n    </MotionConfig>\n  );\n}\n\nexport default KpiCounter;\n"}]}