{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tally-hero",
  "type": "registry:block",
  "title": "Tally Hero",
  "description": "A hero led by one giant figure that rolls up digit by digit as the itemised statement beneath it prints line by line, landing on a total that matches, with a period switch that re-tallies both.",
  "categories": [
    "block",
    "Heroes"
  ],
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "utils",
    "https://coss.com/ui/r/button.json",
    "https://coss.com/ui/r/segmented-control.json"
  ],
  "files": [
    {
      "path": "registry/devl/tally-hero.tsx",
      "type": "registry:component",
      "content": "\"use client\";\n\nimport { ArrowRightIcon, CheckIcon } from \"lucide-react\";\nimport {\n  AnimatePresence,\n  animate,\n  MotionConfig,\n  motion,\n  useInView,\n  useMotionValue,\n  useReducedMotion,\n  useTransform,\n} from \"motion/react\";\nimport { type KeyboardEvent, useEffect, useId, useMemo, useRef, useState } from \"react\";\nimport { Button } from \"@/components/ui/button\";\nimport { SegmentedControl, SegmentedControlItem } from \"@/components/ui/segmented-control\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface TallyLine {\n  label: string;\n  detail?: string;\n  amount: number;\n}\n\nexport interface TallyPeriod {\n  id: string;\n  label: string;\n  range: string;\n  caption: string;\n  lines: TallyLine[];\n}\n\nexport interface TallyHeroProps {\n  periods: TallyPeriod[];\n  defaultPeriod?: string;\n  eyebrow?: string;\n  description?: string;\n  cta: { label: string; href: string };\n  note?: string;\n  statementLabel?: string;\n  totalLabel?: string;\n  reference?: string;\n  reconciledLabel?: string;\n  currency?: string;\n  locale?: string;\n  className?: string;\n}\n\ntype Glyph = { key: string; kind: \"digit\" | \"group\" | \"currency\" | \"literal\"; char: string; place: number };\n\nconst ease = [0.23, 1, 0.32, 1] as const;\nconst hidden = \"inset(0% 100% 0% 0%)\";\nconst shown = \"inset(0% 0% 0% 0%)\";\nconst wheelStiffness = 340;\nconst strip = Array.from({ length: 11 }, (_, slot) => slot);\n\nfunction useReducedMotionSafe() {\n  const prefers = useReducedMotion();\n  const [mounted, setMounted] = useState(false);\n  useEffect(() => setMounted(true), []);\n  return mounted && Boolean(prefers);\n}\n\nfunction toGlyphs(formatter: Intl.NumberFormat, total: number): { glyphs: Glyph[]; places: number } {\n  const parts = formatter.formatToParts(total);\n  const places = parts.filter((p) => p.type === \"integer\").reduce((n, p) => n + p.value.length, 0);\n  let place = places;\n  const glyphs: Glyph[] = [];\n  parts.forEach((part, i) => {\n    if (part.type === \"integer\") {\n      for (const char of part.value) {\n        place--;\n        glyphs.push({ key: `d${place}`, kind: \"digit\", char, place });\n      }\n    } else if (part.type === \"group\") {\n      glyphs.push({ key: `g${place}`, kind: \"group\", char: part.value, place });\n    } else if (part.type === \"currency\") {\n      glyphs.push({ key: place === places ? \"currency\" : \"currency-end\", kind: \"currency\", char: part.value, place: -1 });\n    } else {\n      glyphs.push({ key: `l${i}`, kind: \"literal\", char: part.value, place: -1 });\n    }\n  });\n  return { glyphs, places };\n}\n\nfunction Wheel({ digit, from, direction, delay, reduce }: { digit: number; from: number; direction: number; delay: number; reduce: boolean }) {\n  const turn = useMotionValue(from);\n  const goal = useRef(from);\n  const y = useTransform(turn, (t) => `${-(((t % 10) + 10) % 10) * 1.1}em`);\n\n  useEffect(() => {\n    const at = ((goal.current % 10) + 10) % 10;\n    if (at !== digit) goal.current += direction < 0 ? -((at - digit + 10) % 10) : (digit - at + 10) % 10;\n    if (reduce) {\n      turn.jump(goal.current);\n      return;\n    }\n    if (turn.get() === goal.current) return;\n    const controls = animate(turn, goal.current, {\n      type: \"spring\",\n      stiffness: wheelStiffness,\n      damping: 2 * Math.sqrt(wheelStiffness),\n      delay,\n    });\n    return () => controls.stop();\n  }, [digit, direction, delay, reduce, turn]);\n\n  return (\n    <>\n      <span className=\"invisible block h-[1.1em]\">0</span>\n      <motion.span className=\"absolute inset-x-0 top-0 flex flex-col\" style={{ y }}>\n        {strip.map((slot) => (\n          <span className=\"block h-[1.1em] text-center leading-[1.1em]\" key={slot}>\n            {slot % 10}\n          </span>\n        ))}\n      </motion.span>\n    </>\n  );\n}\n\nfunction Counter({ value, total, formatter, reduce }: { value: number; total: number; formatter: Intl.NumberFormat; reduce: boolean }) {\n  const { glyphs, places } = useMemo(() => toGlyphs(formatter, total), [formatter, total]);\n  const padded = String(Math.round(value)).padStart(places, \"0\");\n  const lit = value > 0 ? String(Math.round(value)).length : 0;\n\n  const previous = useRef(value);\n  const direction = Math.sign(value - previous.current);\n  useEffect(() => {\n    previous.current = value;\n  }, [value]);\n\n  const painted = useRef(false);\n  useEffect(() => {\n    painted.current = true;\n  }, []);\n\n  return (\n    <span aria-hidden className=\"flex items-start\">\n      <AnimatePresence initial={false} mode=\"popLayout\">\n        {glyphs.map((glyph) => {\n          const on = glyph.place < lit;\n          if (glyph.kind === \"currency\") {\n            return (\n              <motion.span\n                className=\"me-[0.06em] mt-[0.32em] font-medium text-[0.42em] text-muted-foreground leading-none tracking-normal\"\n                key={glyph.key}\n                layout={reduce ? false : \"position\"}\n                transition={{ type: \"spring\", duration: 0.4, bounce: 0 }}\n              >\n                {glyph.char}\n              </motion.span>\n            );\n          }\n          return (\n            <motion.span\n              animate={{ opacity: 1 }}\n              className={cn(\n                \"relative inline-block h-[1.1em] leading-[1.1em] transition-colors duration-300\",\n                glyph.kind === \"digit\" &&\n                  \"overflow-hidden [mask-image:linear-gradient(to_bottom,transparent,black_16%,black_84%,transparent)]\",\n                glyph.kind === \"literal\" || on ? \"text-foreground\" : \"text-foreground/15\",\n              )}\n              exit={{ opacity: 0, transition: { duration: 0.1 } }}\n              initial={{ opacity: 0 }}\n              key={glyph.key}\n              layout={reduce ? false : \"position\"}\n              transition={{ type: \"spring\", duration: 0.4, bounce: 0 }}\n            >\n              {glyph.kind === \"digit\" ? (\n                <Wheel\n                  delay={Math.min(glyph.place, 6) * 0.012}\n                  digit={Number(padded[padded.length - 1 - glyph.place])}\n                  direction={direction}\n                  from={painted.current ? 0 : Number(padded[padded.length - 1 - glyph.place])}\n                  reduce={reduce}\n                />\n              ) : (\n                glyph.char\n              )}\n            </motion.span>\n          );\n        })}\n      </AnimatePresence>\n    </span>\n  );\n}\n\nfunction PeriodSwitch({ periods, value, onChange }: { periods: TallyPeriod[]; value: string; onChange: (id: string) => void }) {\n  const refs = useRef<(HTMLButtonElement | null)[]>([]);\n  const index = Math.max(\n    0,\n    periods.findIndex((p) => p.id === value),\n  );\n\n  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n    const moves: Record<string, number> = {\n      ArrowRight: index + 1,\n      ArrowDown: index + 1,\n      ArrowLeft: index - 1,\n      ArrowUp: index - 1,\n      Home: 0,\n      End: periods.length - 1,\n    };\n    if (!(event.key in moves)) return;\n    event.preventDefault();\n    const next = (moves[event.key] + periods.length) % periods.length;\n    onChange(periods[next].id);\n    refs.current[next]?.focus();\n  };\n\n  return (\n    <SegmentedControl aria-label=\"Period\" onKeyDown={onKeyDown} role=\"radiogroup\" size=\"lg\">\n      {periods.map((period, i) => {\n        const checked = i === index;\n        return (\n          <SegmentedControlItem\n            aria-checked={checked}\n            className=\"px-3 text-muted-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n            data-checked={checked ? \"\" : undefined}\n            key={period.id}\n            onClick={() => onChange(period.id)}\n            ref={(el: HTMLButtonElement | null) => {\n              refs.current[i] = el;\n            }}\n            role=\"radio\"\n            tabIndex={checked ? 0 : -1}\n          >\n            {period.label}\n          </SegmentedControlItem>\n        );\n      })}\n    </SegmentedControl>\n  );\n}\n\nexport function TallyHero({\n  periods,\n  defaultPeriod,\n  eyebrow,\n  description,\n  cta,\n  note,\n  statementLabel = \"Statement\",\n  totalLabel = \"Total\",\n  reference,\n  reconciledLabel = \"Reconciled\",\n  currency = \"USD\",\n  locale = \"en-US\",\n  className,\n}: TallyHeroProps) {\n  const ref = useRef<HTMLElement>(null);\n  const headingId = useId();\n  const inView = useInView(ref, { once: true, amount: 0.35 });\n  const reduce = useReducedMotionSafe();\n  const formatter = useMemo(\n    () => new Intl.NumberFormat(locale, { style: \"currency\", currency, maximumFractionDigits: 0, minimumFractionDigits: 0 }),\n    [locale, currency],\n  );\n\n  const [periodId, setPeriodId] = useState(defaultPeriod ?? periods[0]?.id);\n  const period = periods.find((p) => p.id === periodId) ?? periods[0];\n  const lines = period.lines;\n  const total = lines.reduce((sum, line) => sum + line.amount, 0);\n\n  const [printed, setPrinted] = useState(0);\n  const [swapped, setSwapped] = useState(false);\n  const [announcement, setAnnouncement] = useState(\"\");\n\n  useEffect(() => {\n    if (reduce) {\n      setPrinted(Number.POSITIVE_INFINITY);\n      return;\n    }\n    if (!inView) return;\n    const timers: number[] = [];\n    let step = 0;\n    const tick = () => {\n      step++;\n      setPrinted((p) => Math.max(p, step));\n      if (step <= lines.length) timers.push(window.setTimeout(tick, step === lines.length ? 420 : 400));\n    };\n    timers.push(window.setTimeout(tick, 280));\n    return () => timers.forEach(window.clearTimeout);\n  }, [inView, reduce, lines.length]);\n\n  const choose = (id: string) => {\n    if (id === periodId) return;\n    const next = periods.find((p) => p.id === id);\n    if (!next) return;\n    setPeriodId(id);\n    setSwapped(true);\n    setPrinted(Number.POSITIVE_INFINITY);\n    setAnnouncement(`${formatter.format(next.lines.reduce((s, l) => s + l.amount, 0))} ${next.caption}`);\n  };\n\n  const value = lines.slice(0, Math.min(printed, lines.length)).reduce((sum, line) => sum + line.amount, 0);\n  const totalPrinted = printed > lines.length;\n  const sweep = (delay: number) => (reduce ? { duration: 0 } : { duration: 0.26, ease, delay });\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <section\n        aria-labelledby={headingId}\n        className={cn(\"@container mx-auto w-full max-w-[1100px] px-4 py-12 sm:px-10 sm:py-14\", className)}\n        ref={ref}\n      >\n        <div className=\"flex flex-wrap items-center justify-between gap-x-6 gap-y-4\">\n          {eyebrow && <p className=\"font-medium font-mono text-muted-foreground text-xs uppercase tracking-widest\">{eyebrow}</p>}\n          {periods.length > 1 && <PeriodSwitch onChange={choose} periods={periods} value={period.id} />}\n        </div>\n\n        <h1\n          className=\"mt-6 font-heading font-semibold text-[clamp(3rem,18cqi,12rem)] tabular-nums leading-none tracking-[-0.045em] @3xl:mt-8\"\n          id={headingId}\n        >\n          <span className=\"sr-only\">\n            {formatter.format(total)} {period.caption}\n          </span>\n          <Counter formatter={formatter} reduce={reduce} total={total} value={value} />\n        </h1>\n\n        <div className=\"relative mt-6 grid gap-8 @3xl:mt-10 @3xl:grid-cols-[minmax(0,1fr)_minmax(0,26rem)] @3xl:grid-rows-[auto_1fr] @3xl:gap-x-14 @3xl:gap-y-6\">\n          <AnimatePresence initial={false} mode=\"popLayout\">\n            <motion.p\n              animate={{ opacity: 1 }}\n              aria-hidden\n              className=\"max-w-lg text-balance font-heading font-medium text-2xl leading-tight tracking-tight @3xl:text-[1.75rem]\"\n              exit={{ opacity: 0 }}\n              initial={{ opacity: 0 }}\n              key={period.id}\n              transition={{ duration: 0.18, ease }}\n            >\n              {period.caption}\n            </motion.p>\n          </AnimatePresence>\n\n          <div className=\"order-last flex flex-col items-start gap-6 @3xl:order-none @3xl:col-start-1 @3xl:row-start-2 @3xl:self-end\">\n            {description && <p className=\"max-w-md text-pretty text-base text-muted-foreground leading-relaxed\">{description}</p>}\n            <div className=\"flex flex-col items-start gap-3\">\n              <Button\n                className=\"transition-[box-shadow,transform] duration-150 ease-out active:scale-[0.97] motion-reduce:active:scale-100\"\n                render={<a href={cta.href} />}\n                size=\"lg\"\n              >\n                {cta.label}\n                <ArrowRightIcon />\n              </Button>\n              {note && <p className=\"max-w-sm text-pretty text-muted-foreground text-xs leading-relaxed\">{note}</p>}\n            </div>\n          </div>\n\n          <div className=\"@container rounded-2xl border bg-card font-mono text-[0.8125rem] shadow-xs/5 @3xl:col-start-2 @3xl:row-span-2 @3xl:row-start-1\">\n            <div className=\"flex items-baseline justify-between gap-4 border-b border-dashed px-4 py-3 text-muted-foreground text-xs sm:px-5\">\n              <span className=\"uppercase tracking-widest\">{statementLabel}</span>\n              <span className=\"truncate tabular-nums\">{period.range}</span>\n            </div>\n            <dl className=\"px-4 py-2.5 sm:px-5\">\n              {lines.map((line, i) => {\n                const latest = !swapped && !totalPrinted && i === printed - 1;\n                return (\n                  <motion.div\n                    animate={{ clipPath: i < printed ? shown : hidden }}\n                    className=\"flex items-end gap-2 py-1.5\"\n                    initial={{ clipPath: hidden }}\n                    key={`${period.id}-${line.label}`}\n                    transition={sweep(swapped ? i * 0.045 : 0)}\n                  >\n                    <dt className=\"flex min-w-0 items-baseline gap-2\">\n                      <span className=\"truncate\">{line.label}</span>\n                      {line.detail && <span className=\"hidden shrink-0 text-muted-foreground text-xs tabular-nums @sm:inline\">{line.detail}</span>}\n                    </dt>\n                    <span\n                      aria-hidden\n                      className=\"mb-[0.3em] h-1 min-w-4 flex-1 bg-[radial-gradient(circle,currentColor_0.75px,transparent_1.1px)] bg-size-[5px_4px] bg-repeat-x text-foreground/30\"\n                    />\n                    <dd\n                      className={cn(\n                        \"shrink-0 tabular-nums transition-colors duration-500\",\n                        latest ? \"text-success-foreground\" : \"text-foreground\",\n                      )}\n                    >\n                      {formatter.format(line.amount)}\n                    </dd>\n                  </motion.div>\n                );\n              })}\n            </dl>\n            <motion.div\n              animate={{ clipPath: totalPrinted ? shown : hidden }}\n              className=\"mx-4 flex items-baseline justify-between gap-4 border-foreground/70 border-t-[3px] border-double py-3 sm:mx-5\"\n              initial={{ clipPath: hidden }}\n              key={`${period.id}-total`}\n              transition={sweep(swapped ? lines.length * 0.045 + 0.04 : 0)}\n            >\n              <span className=\"font-medium\">{totalLabel}</span>\n              <span className=\"font-semibold text-base tabular-nums\">{formatter.format(total)}</span>\n            </motion.div>\n            <div className=\"flex items-center justify-between gap-4 border-t border-dashed px-4 py-3 text-muted-foreground text-xs sm:px-5\">\n              <span className=\"truncate\">{reference}</span>\n              <motion.span\n                animate={{ opacity: totalPrinted ? 1 : 0 }}\n                className=\"inline-flex shrink-0 items-center gap-1 text-success-foreground\"\n                initial={false}\n                transition={{ duration: reduce ? 0 : 0.2, delay: reduce || swapped ? 0 : 0.2 }}\n              >\n                <CheckIcon className=\"size-3.5\" />\n                {reconciledLabel}\n              </motion.span>\n            </div>\n          </div>\n        </div>\n        <p aria-live=\"polite\" className=\"sr-only\">\n          {announcement}\n        </p>\n      </section>\n    </MotionConfig>\n  );\n}\n"
    }
  ]
}