{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "revenue-overview",
  "type": "registry:block",
  "title": "Revenue Story",
  "description": "A store's revenue told as a story: one big annotated line you can scrub day by day against last period, a plain-sentence summary whose numbers roll, a range switch that morphs the line and moves its notes, and a ranked strip of where the money came from.",
  "categories": [
    "screen",
    "Product"
  ],
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "utils",
    "https://coss.com/ui/r/avatar.json",
    "https://coss.com/ui/r/button.json",
    "https://coss.com/ui/r/empty.json",
    "https://coss.com/ui/r/menu.json",
    "https://coss.com/ui/r/segmented-control.json",
    "https://coss.com/ui/r/tooltip.json"
  ],
  "files": [
    {
      "path": "registry/devl/revenue-overview.tsx",
      "type": "registry:component",
      "content": "\"use client\";\n\nimport {\n  ArrowDownRightIcon,\n  ArrowUpRightIcon,\n  ChartSplineIcon,\n  ChevronDownIcon,\n  ChevronRightIcon,\n  ClipboardIcon,\n  DownloadIcon,\n  HandshakeIcon,\n  HouseIcon,\n  type LucideIcon,\n  MegaphoneIcon,\n  PackageIcon,\n  SettingsIcon,\n  ShoppingBagIcon,\n  TagIcon,\n  TruckIcon,\n  UsersIcon,\n} from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion, useSpring, useTransform } from \"motion/react\";\nimport {\n  type KeyboardEvent,\n  type PointerEvent,\n  type ReactNode,\n  type RefObject,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { Avatar, AvatarFallback } from \"@/components/ui/avatar\";\nimport { Button } from \"@/components/ui/button\";\nimport { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from \"@/components/ui/empty\";\nimport { Menu, MenuItem, MenuPopup, MenuTrigger } from \"@/components/ui/menu\";\nimport { SegmentedControl, SegmentedControlItem } from \"@/components/ui/segmented-control\";\nimport { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from \"@/components/ui/tooltip\";\nimport { cn } from \"@/lib/utils\";\n\nexport type RangeKey = \"7d\" | \"30d\" | \"90d\" | \"12m\";\nexport type MomentKind = \"promo\" | \"pricing\" | \"partner\" | \"incident\";\n\nexport interface RevenueDay {\n  date: string;\n  byChannel: Record<string, number>;\n}\n\nexport interface RevenueChannel {\n  key: string;\n  label: string;\n}\n\nexport interface RevenueMoment {\n  id: string;\n  date: string;\n  endDate?: string;\n  kind: MomentKind;\n  title: string;\n  short?: string;\n  phrase?: string;\n  note: string;\n  channel?: string;\n  weight?: number;\n}\n\nexport interface RevenueStoryProps {\n  days?: RevenueDay[];\n  channels?: RevenueChannel[];\n  moments?: RevenueMoment[];\n  store?: { name: string; plan: string };\n  user?: { name: string; email: string };\n  defaultRange?: RangeKey;\n  onRangeChange?: (range: RangeKey) => void;\n  onNavigate?: (label: string) => void;\n  className?: string;\n}\n\nconst DAY = 86_400_000;\nconst MONTHS = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\nconst WEEKDAYS = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n\nconst pad2 = (n: number) => String(n).padStart(2, \"0\");\nfunction parseDay(iso: string) {\n  const [y, m, d] = iso.split(\"-\").map(Number);\n  return Date.UTC(y, m - 1, d);\n}\nfunction isoOf(t: number) {\n  const d = new Date(t);\n  return `${d.getUTCFullYear()}-${pad2(d.getUTCMonth() + 1)}-${pad2(d.getUTCDate())}`;\n}\nfunction dayLabel(t: number, year?: number) {\n  const d = new Date(t);\n  const base = `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}`;\n  return year !== undefined && d.getUTCFullYear() !== year ? `${base}, ${d.getUTCFullYear()}` : base;\n}\nconst yearOf = (t: number) => new Date(t).getUTCFullYear();\n\nfunction mulberry32(seed: number) {\n  let s = seed;\n  return () => {\n    s = (s + 0x6d2b79f5) | 0;\n    let t = Math.imul(s ^ (s >>> 15), 1 | s);\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\nconst SAMPLE_CHANNELS: RevenueChannel[] = [\n  { key: \"store\", label: \"Online store\" },\n  { key: \"wholesale\", label: \"Wholesale\" },\n  { key: \"market\", label: \"Marketplaces\" },\n  { key: \"social\", label: \"Social shop\" },\n];\n\nconst SAMPLE_MOMENTS: RevenueMoment[] = [\n  {\n    id: \"spring-sale\",\n    date: \"2025-04-24\",\n    endDate: \"2025-04-28\",\n    kind: \"promo\",\n    title: \"Spring sale\",\n    phrase: \"the spring sale\",\n    note: \"20% off throws and bedding for five days, sent to the full list.\",\n    weight: 2,\n  },\n  {\n    id: \"marketplace-fees\",\n    date: \"2025-06-02\",\n    kind: \"pricing\",\n    channel: \"market\",\n    title: \"Marketplace fees went up\",\n    short: \"Marketplace fees\",\n    note: \"Listing fees rose to 9.5%, so marketplace prices went up to cover them.\",\n    weight: 2,\n  },\n  {\n    id: \"autumn-launch\",\n    date: \"2025-09-23\",\n    endDate: \"2025-09-29\",\n    kind: \"promo\",\n    title: \"Autumn collection launch\",\n    short: \"Autumn launch\",\n    phrase: \"the autumn launch\",\n    note: \"Twelve new pieces in walnut and wool, launched with a lookbook email.\",\n    weight: 1,\n  },\n  {\n    id: \"starter-price\",\n    date: \"2025-11-18\",\n    kind: \"pricing\",\n    channel: \"store\",\n    title: \"Price change on Starter Set\",\n    short: \"Starter Set price\",\n    note: \"The Starter Set went from $68 to $58 to make it an easier first order.\",\n    weight: 2,\n  },\n  {\n    id: \"black-friday\",\n    date: \"2025-11-28\",\n    endDate: \"2025-12-01\",\n    kind: \"promo\",\n    title: \"Black Friday sale\",\n    short: \"Black Friday\",\n    phrase: \"the Black Friday sale\",\n    note: \"25% off sitewide through Cyber Monday. Marketplaces ran the same discount.\",\n    weight: 3,\n  },\n  {\n    id: \"wholesale-partner\",\n    date: \"2025-12-02\",\n    kind: \"partner\",\n    channel: \"wholesale\",\n    title: \"Wholesale partner onboarded\",\n    short: \"Wholesale partner\",\n    note: \"Juniper & Pine took 14 lines for their four shops. The first order shipped on Dec 3.\",\n    weight: 3,\n  },\n  {\n    id: \"shipping-delay\",\n    date: \"2025-12-08\",\n    endDate: \"2025-12-10\",\n    kind: \"incident\",\n    title: \"Shipping delay\",\n    phrase: \"the shipping delay\",\n    note: \"A carrier backlog pushed delivery estimates to 6–8 days and checkout conversion fell.\",\n    weight: 3,\n  },\n  {\n    id: \"gift-guide\",\n    date: \"2025-12-11\",\n    endDate: \"2025-12-12\",\n    kind: \"promo\",\n    title: \"Gift guide email\",\n    short: \"Gift guide\",\n    phrase: \"the gift guide email\",\n    note: \"The holiday gift guide went to 41,200 subscribers on Thursday morning.\",\n    weight: 2,\n  },\n];\n\nconst SAMPLE_EFFECTS: { from: string; to: string; on: string[]; by: number[] }[] = [\n  { from: \"2024-11-29\", to: \"2024-12-02\", on: [\"store\", \"market\", \"social\"], by: [1.55, 1.28, 1.22, 1.38] },\n  { from: \"2025-04-24\", to: \"2025-04-28\", on: [\"store\", \"social\"], by: [1.34, 1.26, 1.22, 1.2, 1.14] },\n  { from: \"2025-06-02\", to: \"2025-12-12\", on: [\"market\"], by: [0.84] },\n  { from: \"2025-09-23\", to: \"2025-09-29\", on: [\"store\"], by: [1.26, 1.18, 1.14, 1.1, 1.08, 1.06, 1.04] },\n  { from: \"2025-11-18\", to: \"2025-12-12\", on: [\"store\"], by: [1.04] },\n  { from: \"2025-11-28\", to: \"2025-12-01\", on: [\"store\", \"market\", \"social\"], by: [1.85, 1.42, 1.32, 1.56] },\n  { from: \"2025-12-02\", to: \"2025-12-12\", on: [\"wholesale\"], by: [1.3, 3.6, 2.3] },\n  { from: \"2025-12-08\", to: \"2025-12-10\", on: [\"store\", \"market\"], by: [0.72, 0.6, 0.78] },\n  { from: \"2025-12-11\", to: \"2025-12-12\", on: [\"store\", \"social\"], by: [1.26, 1.12] },\n];\n\nfunction sampleDays(): RevenueDay[] {\n  const rand = mulberry32(1128);\n  const end = Date.UTC(2025, 11, 12);\n  const count = 728;\n  const season = [0.84, 0.82, 0.9, 0.95, 0.97, 0.93, 0.9, 0.92, 0.98, 1.02, 1.03, 1.06];\n  const week = [1.03, 0.94, 0.96, 0.98, 1.0, 1.04, 1.07];\n  const out: RevenueDay[] = [];\n  for (let i = 0; i < count; i++) {\n    const t = end - (count - 1 - i) * DAY;\n    const date = isoOf(t);\n    const d = new Date(t);\n    const p = i / (count - 1);\n    const level = 5400 * (1 + 0.36 * p) * season[d.getUTCMonth()] * week[d.getUTCDay()];\n    const shares: Record<string, number> = {\n      store: 0.5 - 0.03 * p,\n      wholesale: 0.14,\n      market: 0.28 - 0.05 * p,\n      social: 0.08 + 0.07 * p,\n    };\n    const byChannel: Record<string, number> = {};\n    for (const key of Object.keys(shares)) {\n      let boost = 1;\n      for (const e of SAMPLE_EFFECTS) {\n        if (date < e.from || date > e.to || !e.on.includes(key)) continue;\n        const offset = Math.round((t - parseDay(e.from)) / DAY);\n        boost *= e.by[Math.min(offset, e.by.length - 1)];\n      }\n      const spread = key === \"wholesale\" ? 0.5 : 0.14;\n      byChannel[key] = Math.round(level * shares[key] * boost * (1 + (rand() - 0.5) * spread));\n    }\n    out.push({ date, byChannel });\n  }\n  return out;\n}\n\nconst SAMPLE_DAYS = sampleDays();\n\nconst RANGES: { value: RangeKey; label: string; long: string; buckets: number; step: number }[] = [\n  { value: \"7d\", label: \"7d\", long: \"Last 7 days\", buckets: 7, step: 1 },\n  { value: \"30d\", label: \"30d\", long: \"Last 30 days\", buckets: 30, step: 1 },\n  { value: \"90d\", label: \"90d\", long: \"Last 90 days\", buckets: 90, step: 1 },\n  { value: \"12m\", label: \"12m\", long: \"Last 12 months\", buckets: 52, step: 7 },\n];\n\nconst KINDS: Record<MomentKind, { label: string; icon: LucideIcon; dot: string; band: string; stem: string; soft: string }> = {\n  promo: {\n    label: \"Promotion\",\n    icon: MegaphoneIcon,\n    dot: \"fill-violet-500 dark:fill-violet-400\",\n    band: \"fill-violet-500/8 dark:fill-violet-400/7\",\n    stem: \"stroke-violet-500/50 dark:stroke-violet-400/50\",\n    soft: \"bg-violet-500/12 text-violet-700 dark:bg-violet-400/15 dark:text-violet-300\",\n  },\n  pricing: {\n    label: \"Pricing\",\n    icon: TagIcon,\n    dot: \"fill-sky-500 dark:fill-sky-400\",\n    band: \"fill-sky-500/8 dark:fill-sky-400/7\",\n    stem: \"stroke-sky-500/50 dark:stroke-sky-400/50\",\n    soft: \"bg-sky-500/12 text-sky-700 dark:bg-sky-400/15 dark:text-sky-300\",\n  },\n  partner: {\n    label: \"Partner\",\n    icon: HandshakeIcon,\n    dot: \"fill-teal-500 dark:fill-teal-400\",\n    band: \"fill-teal-500/8 dark:fill-teal-400/7\",\n    stem: \"stroke-teal-500/50 dark:stroke-teal-400/50\",\n    soft: \"bg-teal-500/12 text-teal-700 dark:bg-teal-400/15 dark:text-teal-300\",\n  },\n  incident: {\n    label: \"Incident\",\n    icon: TruckIcon,\n    dot: \"fill-amber-500 dark:fill-amber-400\",\n    band: \"fill-amber-500/10 dark:fill-amber-400/7\",\n    stem: \"stroke-amber-500/60 dark:stroke-amber-400/60\",\n    soft: \"bg-amber-500/14 text-amber-700 dark:bg-amber-400/15 dark:text-amber-300\",\n  },\n};\n\nconst SHADES = [\"bg-foreground\", \"bg-foreground/55\", \"bg-foreground/32\", \"bg-foreground/16\"];\n\nconst usd = new Intl.NumberFormat(\"en-US\", { style: \"currency\", currency: \"USD\", maximumFractionDigits: 0 });\nconst money = (n: number) => usd.format(Math.round(n));\nfunction compact(n: number) {\n  const a = Math.abs(n);\n  if (a >= 1e6) return `$${(a / 1e6).toFixed(2)}M`;\n  if (a >= 1e3) return `$${(a / 1e3).toFixed(1)}k`;\n  return `$${Math.round(a)}`;\n}\nconst signed = (n: number) => `${n < 0 ? \"−\" : \"+\"}${compact(n)}`;\nconst percent = (n: number) => `${n < 0 ? \"−\" : \"+\"}${Math.abs(n * 100).toFixed(0)}%`;\nconst tone = (n: number) => (n < 0 ? \"text-destructive-foreground\" : \"text-success-foreground\");\nfunction axisMoney(v: number) {\n  if (v >= 1e6) return `$${+(v / 1e6).toFixed(1)}M`;\n  if (v >= 1e3) return `$${+(v / 1e3).toFixed(1)}k`;\n  return `$${v}`;\n}\nconst totalOf = (day: RevenueDay) => Object.values(day.byChannel).reduce((a, b) => a + b, 0);\n\nconst ease = [0.23, 1, 0.32, 1] as const;\nconst pressable = \"transition-[color,background-color,scale] duration-150 ease-out active:scale-[0.97]\";\n\nfunction useMounted() {\n  const [mounted, setMounted] = useState(false);\n  useEffect(() => setMounted(true), []);\n  return mounted;\n}\n\nfunction useReducedMotionAfterMount() {\n  const prefers = useReducedMotion();\n  return useMounted() && Boolean(prefers);\n}\n\nfunction useElementSize<T extends HTMLElement>(): [RefObject<T | null>, { width: number; height: number }] {\n  const ref = useRef<T>(null);\n  const [size, setSize] = useState({ width: 0, height: 0 });\n  useLayoutEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    setSize({ width: el.clientWidth, height: el.clientHeight });\n    const ro = new ResizeObserver(([entry]) =>\n      setSize({ width: entry.contentRect.width, height: entry.contentRect.height }),\n    );\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, []);\n  return [ref, size];\n}\n\nfunction useTextWidth(ref: RefObject<HTMLElement | null>, ready: boolean) {\n  const [measure, setMeasure] = useState<((text: string, weight: number) => number) | null>(null);\n  useEffect(() => {\n    if (!ready || !ref.current) return;\n    const ctx = document.createElement(\"canvas\").getContext(\"2d\");\n    const family = getComputedStyle(ref.current).fontFamily;\n    if (!ctx) return;\n    setMeasure(() => (text: string, weight: number) => {\n      ctx.font = `${weight} 12px ${family}`;\n      return ctx.measureText(text).width;\n    });\n  }, [ready, ref]);\n  return measure;\n}\n\ninterface Bucket {\n  t: number;\n  value: number;\n  prev: number | null;\n  prevT: number;\n}\n\ninterface Impact {\n  change: number;\n  text: string;\n}\n\ninterface PlacedMoment extends RevenueMoment {\n  i0: number;\n  i1: number;\n  impact: Impact | null;\n}\n\ninterface ChannelRow {\n  key: string;\n  label: string;\n  total: number;\n  prev: number;\n}\n\ninterface Model {\n  range: RangeKey;\n  step: number;\n  buckets: Bucket[];\n  start: number;\n  end: number;\n  prevStart: number | null;\n  prevEnd: number | null;\n  total: number;\n  prevTotal: number | null;\n  channels: ChannelRow[];\n  moments: PlacedMoment[];\n}\n\nfunction impactOf(m: RevenueMoment, days: RevenueDay[], index: Map<string, number>, channels: RevenueChannel[]): Impact | null {\n  const a = index.get(m.date);\n  if (a === undefined) return null;\n  if (m.channel) {\n    const w = Math.min(14, days.length - a, a);\n    if (w < 1) return null;\n    let after = 0;\n    let before = 0;\n    for (let k = 0; k < w; k++) {\n      after += days[a + k].byChannel[m.channel] ?? 0;\n      before += days[a - w + k].byChannel[m.channel] ?? 0;\n    }\n    if (!before) return null;\n    const label = channels.find((c) => c.key === m.channel)?.label ?? m.channel;\n    return {\n      change: after / before - 1,\n      text: `${label} has averaged ${compact(after / w)} a day since, up from ${compact(before / w)}.`,\n    };\n  }\n  const b = Math.min(index.get(m.endDate ?? m.date) ?? a, days.length - 1);\n  const len = b - a + 1;\n  if (a - len < 0) return null;\n  let cur = 0;\n  let prev = 0;\n  for (let k = 0; k < len; k++) {\n    cur += totalOf(days[a + k]);\n    prev += totalOf(days[a - len + k]);\n  }\n  if (!prev) return null;\n  const span = len === 1 ? \"that day\" : `over ${len} days`;\n  const before = len === 1 ? \"the day before\" : `the ${len} days before`;\n  return { change: cur / prev - 1, text: `${compact(cur)} ${span}, against ${compact(prev)} ${before}.` };\n}\n\nfunction buildModel(\n  days: RevenueDay[],\n  channels: RevenueChannel[],\n  moments: RevenueMoment[],\n  index: Map<string, number>,\n  impacts: Map<string, Impact | null>,\n  range: RangeKey,\n): Model {\n  const spec = RANGES.find((r) => r.value === range) ?? RANGES[1];\n  const step = spec.step;\n  const n = Math.max(1, Math.min(spec.buckets, Math.floor(days.length / step)));\n  const span = n * step;\n  const endIdx = days.length;\n  const startIdx = Math.max(0, endIdx - span);\n  const prevIdx = startIdx - span;\n  const sumDays = (from: number, to: number) => {\n    let s = 0;\n    for (let k = from; k < to; k++) s += totalOf(days[k]);\n    return s;\n  };\n  const buckets: Bucket[] = Array.from({ length: n }, (_, b) => {\n    const s = startIdx + b * step;\n    const t = parseDay(days[s].date);\n    return {\n      t,\n      value: sumDays(s, s + step),\n      prev: prevIdx >= 0 ? sumDays(s - span, s - span + step) : null,\n      prevT: t - span * DAY,\n    };\n  });\n  const rows = channels.map((c) => {\n    let total = 0;\n    let prev = 0;\n    for (let k = startIdx; k < endIdx; k++) total += days[k].byChannel[c.key] ?? 0;\n    if (prevIdx >= 0) for (let k = prevIdx; k < startIdx; k++) prev += days[k].byChannel[c.key] ?? 0;\n    return { key: c.key, label: c.label, total, prev };\n  });\n  const placed: PlacedMoment[] = [];\n  for (const m of moments) {\n    const a = index.get(m.date);\n    if (a === undefined) continue;\n    const b = index.get(m.endDate ?? m.date) ?? a;\n    if (b < startIdx || a >= endIdx) continue;\n    placed.push({\n      ...m,\n      i0: Math.floor((Math.max(a, startIdx) - startIdx) / step),\n      i1: Math.floor((Math.min(b, endIdx - 1) - startIdx) / step),\n      impact: impacts.get(m.id) ?? null,\n    });\n  }\n  placed.sort((x, y) => x.i0 - y.i0);\n  const total = buckets.reduce((s, b) => s + b.value, 0);\n  return {\n    range,\n    step,\n    buckets,\n    start: parseDay(days[startIdx].date),\n    end: parseDay(days[endIdx - 1].date),\n    prevStart: prevIdx >= 0 ? parseDay(days[prevIdx].date) : null,\n    prevEnd: prevIdx >= 0 ? parseDay(days[startIdx - 1].date) : null,\n    total,\n    prevTotal: prevIdx >= 0 ? buckets.reduce((s, b) => s + (b.prev ?? 0), 0) : null,\n    channels: rows,\n    moments: placed,\n  };\n}\n\nfunction bucketLabel(model: Model, t: number, long = false) {\n  if (model.step === 7) return `${long ? \"Week of \" : \"week of \"}${dayLabel(t, yearOf(model.end))}`;\n  const label = dayLabel(t, yearOf(model.end));\n  return long ? `${WEEKDAYS[new Date(t).getUTCDay()]}, ${label}` : label;\n}\n\nfunction momentDates(m: RevenueMoment) {\n  const a = parseDay(m.date);\n  if (!m.endDate || m.endDate === m.date) return dayLabel(a);\n  return `${dayLabel(a)} – ${dayLabel(parseDay(m.endDate))}`;\n}\n\nfunction momentAt(model: Model, i: number) {\n  return model.moments\n    .filter((m) => m.phrase && i >= m.i0 && i <= m.i1)\n    .sort((a, b) => (b.weight ?? 1) - (a.weight ?? 1))[0];\n}\n\nfunction tangents(ys: number[]) {\n  const n = ys.length;\n  const m = new Array<number>(n).fill(0);\n  if (n < 2) return m;\n  const d = ys.slice(1).map((y, i) => y - ys[i]);\n  m[0] = d[0];\n  m[n - 1] = d[n - 2];\n  for (let i = 1; i < n - 1; i++) m[i] = d[i - 1] * d[i] <= 0 ? 0 : (d[i - 1] + d[i]) / 2;\n  for (let i = 0; i < n - 1; i++) {\n    if (d[i] === 0) {\n      m[i] = 0;\n      m[i + 1] = 0;\n      continue;\n    }\n    const a = m[i] / d[i];\n    const b = m[i + 1] / d[i];\n    const s = a * a + b * b;\n    if (s > 9) {\n      const k = 3 / Math.sqrt(s);\n      m[i] = k * a * d[i];\n      m[i + 1] = k * b * d[i];\n    }\n  }\n  return m;\n}\n\nconst SAMPLES = 271;\n\nfunction resample(values: number[]): { at: number; v: number }[] {\n  const n = values.length;\n  if (n < 2) return Array.from({ length: SAMPLES }, () => ({ at: 0, v: values[0] ?? 0 }));\n  const m = tangents(values);\n  const total = SAMPLES - 1;\n  const out: { at: number; v: number }[] = [];\n  for (let j = 0; j < n - 1; j++) {\n    const sub = Math.floor(((j + 1) * total) / (n - 1)) - Math.floor((j * total) / (n - 1));\n    for (let k = 0; k < sub; k++) {\n      const u = k / sub;\n      const u2 = u * u;\n      const u3 = u2 * u;\n      out.push({\n        at: j + u,\n        v: (2 * u3 - 3 * u2 + 1) * values[j] + (u3 - 2 * u2 + u) * m[j] + (-2 * u3 + 3 * u2) * values[j + 1] + (u3 - u2) * m[j + 1],\n      });\n    }\n  }\n  out.push({ at: n - 1, v: values[n - 1] });\n  return out;\n}\n\nfunction niceTicks(max: number) {\n  const raw = Math.max(max, 1) / 4;\n  const exp = 10 ** Math.floor(Math.log10(raw));\n  const f = raw / exp;\n  const step = (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10) * exp;\n  const count = Math.ceil(max / step);\n  return Array.from({ length: count + 1 }, (_, k) => k * step);\n}\n\nfunction axisTicks(model: Model, plotW: number) {\n  const n = model.buckets.length;\n  const room = Math.max(3, Math.floor(plotW / 72));\n  if (model.step === 7) {\n    const starts = model.buckets\n      .map((b, i) => ({ i, m: new Date(b.t).getUTCMonth() }))\n      .filter((b, k, all) => k > 0 && b.m !== all[k - 1].m)\n      .map((b) => b.i);\n    const every = Math.max(1, Math.ceil(starts.length / room));\n    return starts.filter((_, k) => (starts.length - 1 - k) % every === 0);\n  }\n  const every = Math.max(1, Math.ceil((n - 1) / (room - 1)));\n  const out: number[] = [];\n  for (let i = n - 1; i >= 0; i -= every) out.unshift(i);\n  return out;\n}\n\nfunction placeChips(\n  items: { id: string; x: number; weight: number; full: number }[],\n  left: number,\n  right: number,\n  rows: number,\n  labels: boolean,\n) {\n  const taken: [number, number][][] = Array.from({ length: rows }, () => []);\n  const out = new Map<string, { left: number; row: number; compact: boolean }>();\n  const order = [...items].sort((a, b) => b.weight - a.weight || a.x - b.x);\n  for (const item of order) {\n    const widths = labels ? [item.full, 24] : [24];\n    let done = false;\n    for (const w of widths) {\n      for (let row = 0; row < rows && !done; row++) {\n        const l = Math.min(Math.max(item.x - w / 2, left), right - w);\n        if (taken[row].every(([a, b]) => l + w + 6 <= a || l >= b + 6)) {\n          taken[row].push([l, l + w]);\n          out.set(item.id, { left: l, row, compact: w === 24 });\n          done = true;\n        }\n      }\n      if (done) break;\n    }\n  }\n  return out;\n}\n\nfunction Rolling({ value, format, className }: { value: number; format: (n: number) => string; className?: string }) {\n  const reduce = useReducedMotionAfterMount();\n  const spring = useSpring(value, { stiffness: 240, damping: 34 });\n  const text = useTransform(spring, (v) => format(v));\n  useEffect(() => {\n    if (reduce) spring.jump(value);\n    else spring.set(value);\n  }, [value, reduce, spring]);\n  return <motion.span className={cn(\"tabular-nums\", className)}>{text}</motion.span>;\n}\n\nfunction RangeSwitch({ value, onChange }: { value: RangeKey; onChange: (v: RangeKey) => void }) {\n  const refs = useRef<(HTMLButtonElement | null)[]>([]);\n  const index = Math.max(\n    0,\n    RANGES.findIndex((r) => r.value === value),\n  );\n  const onKeyDown = (e: 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: RANGES.length - 1,\n    };\n    if (!(e.key in moves)) return;\n    e.preventDefault();\n    const next = (moves[e.key] + RANGES.length) % RANGES.length;\n    onChange(RANGES[next].value);\n    refs.current[next]?.focus();\n  };\n  return (\n    <SegmentedControl aria-label=\"Date range\" onKeyDown={onKeyDown} role=\"radiogroup\" size=\"sm\">\n      {RANGES.map((r, i) => {\n        const checked = r.value === value;\n        return (\n          <SegmentedControlItem\n            aria-checked={checked}\n            aria-label={r.long}\n            className=\"min-w-11 px-2.5 text-muted-foreground text-xs tabular-nums focus-visible:ring-2 focus-visible:ring-ring\"\n            data-checked={checked ? \"\" : undefined}\n            key={r.value}\n            onClick={() => onChange(r.value)}\n            ref={(el: HTMLButtonElement | null) => {\n              refs.current[i] = el;\n            }}\n            role=\"radio\"\n            tabIndex={checked ? 0 : -1}\n          >\n            {r.label}\n          </SegmentedControlItem>\n        );\n      })}\n    </SegmentedControl>\n  );\n}\n\nfunction Highlight({ children, className }: { children: ReactNode; className?: string }) {\n  return <span className={cn(\"font-semibold text-foreground\", className)}>{children}</span>;\n}\n\nfunction Summary({ model }: { model: Model }) {\n  const change = model.prevTotal === null ? null : model.total - model.prevTotal;\n  const gains = model.channels.map((c) => ({ label: c.label, delta: c.total - c.prev }));\n  const lead = change === null ? null : [...gains].sort((a, b) => (change >= 0 ? b.delta - a.delta : a.delta - b.delta))[0];\n  const most = lead && change ? lead.delta / change >= 0.5 : false;\n  const unit = model.step === 7 ? \"week\" : \"day\";\n  const values = model.buckets.map((b) => b.value);\n  const best = values.indexOf(Math.max(...values));\n  const worst = values.indexOf(Math.min(...values));\n  const bestMoment = momentAt(model, best);\n  const worstMoment = momentAt(model, worst);\n  const when = (i: number) => (model.step === 7 ? `the ${bucketLabel(model, model.buckets[i].t)}` : bucketLabel(model, model.buckets[i].t));\n\n  return (\n    <div className=\"min-w-0 @3xl:min-h-24\">\n      <p className=\"max-w-[46rem] text-balance font-heading text-[22px] text-muted-foreground leading-[1.3] tracking-[-0.015em] @3xl:text-[27px] @3xl:leading-[1.25]\">\n        <Highlight>\n          <Rolling format={money} value={model.total} />\n        </Highlight>{\" \"}\n        this period\n        {change !== null && lead ? (\n          <>\n            ,{\" \"}\n            <Highlight className={tone(change)}>\n              {change < 0 ? \"down\" : \"up\"} <Rolling format={compact} value={Math.abs(change)} />\n            </Highlight>{\" \"}\n            on the last one — {most ? (change < 0 ? \"mostly from\" : \"most of it from\") : \"led by\"}{\" \"}\n            <Highlight>{lead.label}</Highlight>.\n          </>\n        ) : (\n          \".\"\n        )}\n      </p>\n      <p className=\"mt-2 text-pretty text-muted-foreground text-sm\">\n        Best {unit} was <span className=\"font-medium text-foreground\">{when(best)}</span> at{\" \"}\n        <span className=\"font-medium text-foreground tabular-nums\">{compact(values[best])}</span>\n        {bestMoment ? `, during ${bestMoment.phrase}` : \"\"}. Slowest was{\" \"}\n        <span className=\"font-medium text-foreground\">{when(worst)}</span> at{\" \"}\n        <span className=\"font-medium text-foreground tabular-nums\">{compact(values[worst])}</span>\n        {worstMoment ? `, during ${worstMoment.phrase}` : \"\"}.\n      </p>\n    </div>\n  );\n}\n\ninterface MomentHandlers {\n  openId: string | null;\n  pinnedId: string | null;\n  onHover: (id: string | null) => void;\n  onFocus: (id: string | null) => void;\n  onToggle: (id: string) => void;\n}\n\nfunction KindIcon({ kind, className }: { kind: MomentKind; className?: string }) {\n  const k = KINDS[kind];\n  return (\n    <span aria-hidden className={cn(\"flex shrink-0 items-center justify-center rounded-full\", k.soft, className)}>\n      <k.icon className=\"size-[0.7rem]\" strokeWidth={2.25} />\n    </span>\n  );\n}\n\nfunction StoryChart({ model, handlers, cardId }: { model: Model; handlers: MomentHandlers; cardId: string }) {\n  const mounted = useMounted();\n  const reduce = useReducedMotionAfterMount();\n  const clipId = `reveal-${useId().replace(/:/g, \"\")}`;\n  const fadeId = `fade-${useId().replace(/:/g, \"\")}`;\n  const [surfaceRef, size] = useElementSize<HTMLDivElement>();\n  const ready = mounted && size.width > 0 && size.height > 0;\n  const measure = useTextWidth(surfaceRef, ready);\n  const [scrub, setScrub] = useState<{ range: RangeKey; i: number } | null>(null);\n  const [focused, setFocused] = useState(false);\n\n  const { buckets } = model;\n  const n = buckets.length;\n  const width = size.width;\n  const height = size.height;\n  const wide = width >= 560;\n  const rows = wide ? 2 : 1;\n  const pad = { l: 44, r: 12, t: wide ? 74 : 44, b: 28 };\n  const plotW = Math.max(1, width - pad.l - pad.r);\n  const base = Math.max(pad.t + 1, height - pad.b);\n  const plotH = base - pad.t;\n  const values = useMemo(() => buckets.map((b) => b.value), [buckets]);\n  const prevValues = useMemo(() => (buckets.every((b) => b.prev !== null) ? buckets.map((b) => b.prev ?? 0) : null), [buckets]);\n  const ticks = niceTicks(Math.max(...values, ...(prevValues ?? [0])) * 1.04);\n  const top = ticks[ticks.length - 1] || 1;\n  const x = (i: number) => pad.l + (n === 1 ? plotW / 2 : (i / (n - 1)) * plotW);\n  const y = (v: number) => base - (v / top) * plotH;\n  const morph = reduce ? { duration: 0 } : ({ type: \"spring\", visualDuration: 0.38, bounce: 0 } as const);\n\n  const samples = useMemo(() => resample(values), [values]);\n  const prevSamples = useMemo(() => (prevValues ? resample(prevValues) : null), [prevValues]);\n  const toPath = (pts: { at: number; v: number }[]) =>\n    pts.map((p, k) => `${k ? \"L\" : \"M\"}${x(p.at).toFixed(1)},${y(p.v).toFixed(1)}`).join(\"\");\n  const line = toPath(samples);\n  const area = `${line}L${x(n - 1).toFixed(1)},${base}L${x(0).toFixed(1)},${base}Z`;\n  const prevLine = prevSamples ? toPath(prevSamples) : null;\n\n  const open = model.moments.find((m) => m.id === handlers.openId) ?? null;\n  const scrubIndex = scrub && scrub.range === model.range ? Math.min(scrub.i, n - 1) : null;\n  const active = scrubIndex ?? open?.i0 ?? n - 1;\n  const showCrosshair = scrubIndex !== null || open !== null;\n  const bucket = buckets[active];\n  const delta = bucket.prev ? bucket.value / bucket.prev - 1 : null;\n  const here = model.moments.filter((m) => active >= m.i0 && active <= m.i1);\n  const label = bucketLabel(model, bucket.t, true);\n  const prevLabel = model.step === 7 ? bucketLabel(model, bucket.prevT) : dayLabel(bucket.prevT, yearOf(model.end));\n  const widest = money(Math.max(...values)).length;\n\n  const chipText = (m: PlacedMoment) => ({ label: m.short ?? m.title, delta: m.impact ? percent(m.impact.change) : \"\" });\n  const placement = useMemo(() => {\n    if (!ready) return new Map<string, { left: number; row: number; compact: boolean }>();\n    const items = model.moments.map((m) => {\n      const t = chipText(m);\n      const textW = measure ? measure(t.label, 500) + measure(t.delta, 400) : (t.label.length + t.delta.length) * 6.6;\n      return { id: m.id, x: x(m.i0), weight: m.weight ?? 1, full: Math.ceil(textW + 46) };\n    });\n    return placeChips(items, pad.l - 10, width - 2, rows, wide);\n  }, [ready, model, measure, width, rows, wide]);\n\n  const xTicks = ready ? axisTicks(model, plotW) : [];\n  const valueText = `${label}: ${money(bucket.value)}${delta !== null ? `, ${delta < 0 ? \"down\" : \"up\"} ${Math.abs(delta * 100).toFixed(0)}% on ${prevLabel}` : \"\"}`;\n\n  const indexAt = (e: PointerEvent<HTMLDivElement>) => {\n    const rect = e.currentTarget.getBoundingClientRect();\n    const scale = rect.width / (width || 1);\n    const px = (e.clientX - rect.left) / (scale || 1);\n    return Math.min(n - 1, Math.max(0, Math.round(((px - pad.l) / plotW) * (n - 1))));\n  };\n\n  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {\n    const jump = e.shiftKey ? 7 : 1;\n    const moves: Record<string, number> = {\n      ArrowRight: active + jump,\n      ArrowUp: active + jump,\n      ArrowLeft: active - jump,\n      ArrowDown: active - jump,\n      PageUp: active + 7,\n      PageDown: active - 7,\n      Home: 0,\n      End: n - 1,\n    };\n    if (e.key === \"Escape\") {\n      setScrub(null);\n      return;\n    }\n    if (!(e.key in moves)) return;\n    e.preventDefault();\n    setScrub({ range: model.range, i: Math.min(n - 1, Math.max(0, moves[e.key])) });\n  };\n\n  const cardW = wide ? 248 : Math.max(0, width - 8);\n  const cardX = open ? x(open.i0) : 0;\n  const cardRight = cardX + 14 + cardW <= width - 4;\n  const cardLeft = wide ? (cardRight ? cardX + 14 : Math.max(4, cardX - 14 - cardW)) : 4;\n  const cardTop = pad.t + 2;\n\n  return (\n    <section aria-label=\"Revenue chart\" className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n      <div className=\"flex flex-wrap items-end justify-between gap-x-6 gap-y-3\">\n        <div className=\"min-w-0\">\n          <div className=\"flex h-5 min-w-0 items-center gap-2 text-muted-foreground text-xs\">\n            <span className=\"shrink-0 tabular-nums\">{showCrosshair || focused ? label : `Latest · ${label}`}</span>\n            {here[0] && (\n              <span className={cn(\"inline-flex h-5 min-w-0 items-center gap-1 rounded-full ps-0.5 pe-2 font-medium\", KINDS[here[0].kind].soft)}>\n                <KindIcon className=\"size-4 bg-transparent\" kind={here[0].kind} />\n                <span className=\"truncate\">{here[0].title}</span>\n              </span>\n            )}\n          </div>\n          <div className=\"mt-1.5 flex flex-wrap items-baseline gap-x-3 gap-y-1\">\n            <span\n              className=\"font-heading font-semibold text-[28px] leading-none tracking-[-0.02em] tabular-nums\"\n              style={{ minWidth: `${widest * 0.6}em` }}\n            >\n              {money(bucket.value)}\n            </span>\n            {delta !== null && bucket.prev !== null && (\n              <span className=\"inline-flex items-center gap-1 text-xs tabular-nums\">\n                <span className={cn(\"inline-flex items-center gap-0.5 font-medium\", tone(delta))}>\n                  {delta < 0 ? <ArrowDownRightIcon aria-hidden className=\"size-3.5\" /> : <ArrowUpRightIcon aria-hidden className=\"size-3.5\" />}\n                  {percent(delta)}\n                </span>\n                <span className=\"text-muted-foreground\">\n                  vs {prevLabel} · {money(bucket.prev)}\n                </span>\n              </span>\n            )}\n          </div>\n        </div>\n        <div aria-hidden className=\"flex items-center gap-4 pb-0.5 text-muted-foreground text-xs\">\n          <span className=\"inline-flex items-center gap-1.5\">\n            <span className=\"h-0.5 w-4 rounded-full bg-foreground\" />\n            This period\n          </span>\n          {prevValues && (\n            <span className=\"inline-flex items-center gap-1.5\">\n              <svg className=\"h-0.5 w-4 overflow-visible\" viewBox=\"0 0 16 2\">\n                <line className=\"stroke-muted-foreground/70\" strokeDasharray=\"3 3\" strokeWidth={1.5} x1={0} x2={16} y1={1} y2={1} />\n              </svg>\n              Previous period\n            </span>\n          )}\n        </div>\n      </div>\n\n      <div\n        className=\"relative mt-3 h-[300px] min-h-0 w-full @4xl:h-auto @4xl:min-h-[260px] @4xl:flex-1\"\n        onKeyDown={(e) => {\n          if (e.key === \"Escape\" && handlers.pinnedId) handlers.onToggle(handlers.pinnedId);\n        }}\n      >\n        <div\n          aria-label=\"Scrub revenue\"\n          aria-valuemax={n - 1}\n          aria-valuemin={0}\n          aria-valuenow={active}\n          aria-valuetext={valueText}\n          className=\"absolute inset-0 cursor-crosshair touch-pan-y rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n          onBlur={() => {\n            setFocused(false);\n            setScrub(null);\n          }}\n          onFocus={() => setFocused(true)}\n          onKeyDown={onKeyDown}\n          onPointerDown={(e) => {\n            if (handlers.pinnedId) handlers.onToggle(handlers.pinnedId);\n            setScrub({ range: model.range, i: indexAt(e) });\n          }}\n          onPointerLeave={() => setScrub(null)}\n          onPointerMove={(e) => setScrub({ range: model.range, i: indexAt(e) })}\n          ref={surfaceRef}\n          role=\"slider\"\n          tabIndex={0}\n        >\n          {ready && (\n            <svg aria-hidden className=\"absolute inset-0 overflow-visible\" height={height} width={width}>\n              <defs>\n                <clipPath id={clipId}>\n                  <motion.rect\n                    animate={{ width: width + 8 }}\n                    height={height + 8}\n                    initial={{ width: reduce ? width + 8 : 0 }}\n                    transition={reduce ? { duration: 0 } : { duration: 0.7, ease }}\n                    x={-4}\n                    y={-4}\n                  />\n                </clipPath>\n                <linearGradient id={fadeId} x1=\"0\" x2=\"0\" y1=\"0\" y2=\"1\">\n                  <stop className=\"[stop-color:var(--color-foreground)]\" offset=\"0%\" stopOpacity={0.09} />\n                  <stop className=\"[stop-color:var(--color-foreground)]\" offset=\"100%\" stopOpacity={0} />\n                </linearGradient>\n              </defs>\n\n              {model.moments\n                .filter((m) => m.endDate && m.endDate !== m.date)\n                .map((m) => {\n                  const half = n > 1 ? plotW / (n - 1) / 2 : plotW / 2;\n                  const left = Math.max(pad.l, x(m.i0) - half);\n                  const right = Math.min(pad.l + plotW, x(m.i1) + half);\n                  return (\n                    <motion.rect\n                      animate={{ x: left, width: Math.max(2, right - left), opacity: 1 }}\n                      className={KINDS[m.kind].band}\n                      height={plotH}\n                      initial={{ x: left, width: Math.max(2, right - left), opacity: 0 }}\n                      key={`band-${m.id}`}\n                      rx={4}\n                      transition={{ x: morph, width: morph, opacity: { duration: 0.2 } }}\n                      y={pad.t}\n                    />\n                  );\n                })}\n\n              {ticks.map((v, k) => (\n                <motion.g animate={{ y: y(v) }} initial={false} key={`tick-${k}`} transition={morph}>\n                  <line\n                    className={k === 0 ? \"stroke-border\" : \"stroke-border/70\"}\n                    strokeDasharray={k === 0 ? undefined : \"2 4\"}\n                    x1={pad.l}\n                    x2={width - pad.r}\n                    y1={0}\n                    y2={0}\n                  />\n                  <text className=\"fill-muted-foreground text-[10px] tabular-nums\" dominantBaseline=\"middle\" textAnchor=\"end\" x={pad.l - 10} y={0}>\n                    {axisMoney(v)}\n                  </text>\n                </motion.g>\n              ))}\n\n              {xTicks.map((i) => {\n                const px = x(i);\n                const anchor = i === n - 1 && n > 1 ? \"end\" : px - 24 < pad.l ? \"start\" : \"middle\";\n                const t = buckets[i].t;\n                return (\n                  <motion.text\n                    animate={{ opacity: 1 }}\n                    className=\"fill-muted-foreground text-[10px] tabular-nums\"\n                    initial={{ opacity: 0 }}\n                    key={`${model.range}-${i}`}\n                    textAnchor={anchor}\n                    transition={{ duration: reduce ? 0 : 0.18 }}\n                    x={px}\n                    y={height - 8}\n                  >\n                    {model.step === 7 ? MONTHS[new Date(t + 6 * DAY).getUTCMonth()] : dayLabel(t)}\n                  </motion.text>\n                );\n              })}\n\n              <g clipPath={`url(#${clipId})`}>\n                {prevLine && (\n                  <motion.path\n                    animate={{ d: prevLine }}\n                    className=\"fill-none stroke-muted-foreground/55\"\n                    initial={false}\n                    strokeDasharray=\"3 4\"\n                    strokeLinecap=\"round\"\n                    strokeWidth={1.5}\n                    transition={morph}\n                  />\n                )}\n                <motion.path animate={{ d: area }} fill={`url(#${fadeId})`} initial={false} transition={morph} />\n                <motion.path\n                  animate={{ d: line }}\n                  className=\"fill-none stroke-foreground\"\n                  initial={false}\n                  strokeLinecap=\"round\"\n                  strokeLinejoin=\"round\"\n                  strokeWidth={2}\n                  transition={morph}\n                />\n              </g>\n\n              {model.moments.map((m) => {\n                const spot = placement.get(m.id);\n                const cx = x(m.i0);\n                const cy = y(values[m.i0]);\n                const settle = { duration: reduce ? 0 : 0.2, delay: reduce ? 0 : 0.36 };\n                return (\n                  <motion.g animate={{ opacity: 1 }} initial={{ opacity: 0 }} key={`mark-${model.range}-${m.id}`} transition={settle}>\n                    {spot && <line className={KINDS[m.kind].stem} strokeDasharray=\"2 3\" x1={cx} x2={cx} y1={spot.row * 30 + 28} y2={cy - 7} />}\n                    <circle className={cn(\"stroke-background\", KINDS[m.kind].dot)} cx={cx} cy={cy} r={spot ? 4.5 : 3.5} strokeWidth={2} />\n                  </motion.g>\n                );\n              })}\n\n              {showCrosshair ? (\n                <g>\n                  <line className=\"stroke-foreground/25\" x1={x(active)} x2={x(active)} y1={pad.t - 4} y2={base} />\n                  {prevValues && (\n                    <circle className=\"fill-background stroke-muted-foreground\" cx={x(active)} cy={y(prevValues[active])} r={3} strokeWidth={1.5} />\n                  )}\n                  <circle className=\"fill-foreground stroke-background\" cx={x(active)} cy={y(values[active])} r={4.5} strokeWidth={2} />\n                </g>\n              ) : (\n                <motion.circle\n                  animate={{ opacity: 1 }}\n                  className=\"fill-foreground stroke-background\"\n                  cx={x(n - 1)}\n                  cy={y(values[n - 1])}\n                  initial={{ opacity: 0 }}\n                  key={`end-${model.range}`}\n                  r={4}\n                  strokeWidth={2}\n                  transition={{ duration: reduce ? 0 : 0.2, delay: reduce ? 0 : 0.36 }}\n                />\n              )}\n            </svg>\n          )}\n        </div>\n\n        <AnimatePresence initial={!reduce}>\n          {ready &&\n            model.moments.map((m) => {\n              const spot = placement.get(m.id);\n              if (!spot) return null;\n              const text = chipText(m);\n              const isOpen = handlers.openId === m.id;\n              return (\n                <motion.button\n                  animate={{ x: spot.left, y: spot.row * 30 + 4, opacity: 1, scale: 1 }}\n                  aria-controls={isOpen ? cardId : undefined}\n                  aria-expanded={isOpen}\n                  aria-label={`Chart note: ${m.title}, ${momentDates(m)}`}\n                  className={cn(\n                    \"absolute top-0 left-0 z-10 inline-flex h-6 cursor-pointer items-center gap-1.5 whitespace-nowrap rounded-full border bg-background text-xs shadow-xs/5 outline-none before:absolute before:-inset-x-1 before:-inset-y-1 focus-visible:ring-2 focus-visible:ring-ring\",\n                    \"transition-[background-color,border-color,scale] duration-150 ease-out active:scale-[0.97] [@media(hover:hover)]:hover:bg-accent\",\n                    spot.compact ? \"w-6 justify-center\" : \"ps-[3px] pe-2\",\n                    isOpen && \"border-foreground/25 bg-accent\",\n                  )}\n                  exit={{ opacity: 0, scale: 0.95, transition: { duration: 0.12 } }}\n                  initial={{ x: spot.left, y: spot.row * 30 + 4, opacity: 0, scale: 0.95 }}\n                  key={m.id}\n                  onBlur={() => handlers.onFocus(null)}\n                  onClick={() => handlers.onToggle(m.id)}\n                  onFocus={() => handlers.onFocus(m.id)}\n                  onPointerEnter={(e) => e.pointerType === \"mouse\" && handlers.onHover(m.id)}\n                  onPointerLeave={() => handlers.onHover(null)}\n                  transition={{\n                    x: morph,\n                    y: morph,\n                    opacity: { duration: 0.18, delay: reduce ? 0 : 0.45 },\n                    scale: { duration: 0.18, ease, delay: reduce ? 0 : 0.45 },\n                  }}\n                  type=\"button\"\n                >\n                  <KindIcon className=\"size-4\" kind={m.kind} />\n                  {!spot.compact && (\n                    <>\n                      <span className=\"font-medium\">{text.label}</span>\n                      {text.delta && <span className=\"text-muted-foreground tabular-nums\">{text.delta}</span>}\n                    </>\n                  )}\n                </motion.button>\n              );\n            })}\n        </AnimatePresence>\n\n        <AnimatePresence>\n          {ready && open && (\n            <motion.div\n              animate={{ opacity: 1, scale: 1, x: cardLeft, y: cardTop }}\n              className=\"pointer-events-none absolute top-0 left-0 z-20 rounded-xl border bg-popover p-3 text-popover-foreground shadow-lg/5\"\n              exit={{ opacity: 0, scale: 0.97, transition: { duration: 0.12 } }}\n              id={cardId}\n              initial={{ opacity: 0, scale: 0.97, x: cardLeft, y: cardTop }}\n              key=\"note\"\n              role=\"note\"\n              style={{ width: cardW, originX: wide ? (cardRight ? 0 : 1) : 0.5, originY: 0 }}\n              transition={reduce ? { duration: 0 } : { duration: 0.16, ease, x: { type: \"spring\", visualDuration: 0.2, bounce: 0 } }}\n            >\n              <div className=\"flex items-center gap-2 text-muted-foreground text-xs\">\n                <KindIcon className=\"size-5\" kind={open.kind} />\n                <span>{KINDS[open.kind].label}</span>\n                <span aria-hidden>·</span>\n                <span className=\"tabular-nums\">{momentDates(open)}</span>\n              </div>\n              <p className=\"mt-2 font-medium text-sm\">{open.title}</p>\n              <p className=\"mt-1 text-pretty text-muted-foreground text-xs leading-relaxed\">{open.note}</p>\n              {open.impact && (\n                <div className=\"mt-2.5 flex items-start justify-between gap-3 border-t pt-2.5 text-xs\">\n                  <span className=\"text-pretty text-muted-foreground\">{open.impact.text}</span>\n                  <span className={cn(\"shrink-0 font-medium tabular-nums\", tone(open.impact.change))}>{percent(open.impact.change)}</span>\n                </div>\n              )}\n            </motion.div>\n          )}\n        </AnimatePresence>\n      </div>\n    </section>\n  );\n}\n\nfunction Breakdown({ model }: { model: Model }) {\n  const titleId = useId();\n  const reduce = useReducedMotionAfterMount();\n  const [hover, setHover] = useState<string | null>(null);\n  const ranked = [...model.channels].sort((a, b) => b.total - a.total);\n  const total = ranked.reduce((s, c) => s + c.total, 0) || 1;\n  const hasPrev = model.prevTotal !== null;\n  return (\n    <section aria-labelledby={titleId} className=\"min-w-0\">\n      <div className=\"flex items-baseline justify-between gap-3\">\n        <h2 className=\"font-medium text-sm\" id={titleId}>\n          Where it came from\n        </h2>\n        {hasPrev && <span className=\"text-muted-foreground text-xs\">vs last period</span>}\n      </div>\n      <div\n        aria-label={`Share of revenue: ${ranked.map((c) => `${c.label} ${Math.round((c.total / total) * 100)}%`).join(\", \")}`}\n        className=\"mt-3 flex h-2.5 gap-[3px]\"\n        role=\"img\"\n      >\n        {ranked.map((c, i) => (\n          <div\n            className={cn(\n              \"h-full min-w-1 basis-0 rounded-full transition-[flex-grow,opacity] duration-300 ease-out motion-reduce:transition-none\",\n              SHADES[i % SHADES.length],\n              hover && hover !== c.key && \"opacity-30\",\n            )}\n            key={c.key}\n            style={{ flexGrow: c.total }}\n          />\n        ))}\n      </div>\n      <ol className=\"-mx-2 mt-2 flex flex-col\">\n        {ranked.map((c, i) => {\n          const change = c.total - c.prev;\n          return (\n            <motion.li\n              className=\"grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-3 rounded-lg px-2 py-1 transition-colors duration-150 [@media(hover:hover)]:hover:bg-accent/60\"\n              key={c.key}\n              layout={reduce ? false : \"position\"}\n              onPointerEnter={(e) => e.pointerType === \"mouse\" && setHover(c.key)}\n              onPointerLeave={() => setHover(null)}\n              transition={{ type: \"spring\", visualDuration: 0.3, bounce: 0 }}\n            >\n              <span aria-hidden className={cn(\"size-2.5 rounded-full transition-colors duration-300\", SHADES[i % SHADES.length])} />\n              <div className=\"min-w-0\">\n                <div className=\"truncate\">{c.label}</div>\n                <div className=\"text-muted-foreground text-xs tabular-nums\">{Math.round((c.total / total) * 100)}% of revenue</div>\n              </div>\n              <div className=\"text-right\">\n                <Rolling className=\"font-medium\" format={compact} value={c.total} />\n                {hasPrev && (\n                  <div className={cn(\"text-xs tabular-nums\", tone(change))}>\n                    {signed(change)} · {c.prev ? percent(change / c.prev) : \"new\"}\n                  </div>\n                )}\n              </div>\n            </motion.li>\n          );\n        })}\n      </ol>\n    </section>\n  );\n}\n\nfunction MomentList({ model, handlers, cardId }: { model: Model; handlers: MomentHandlers; cardId: string }) {\n  const titleId = useId();\n  return (\n    <section aria-labelledby={titleId} className=\"flex min-h-0 min-w-0 flex-col\">\n      <div className=\"flex items-baseline justify-between gap-3\">\n        <h2 className=\"font-medium text-sm\" id={titleId}>\n          Moments\n        </h2>\n        <span className=\"text-muted-foreground text-xs tabular-nums\">\n          {model.moments.length ? `${model.moments.length} in this period` : \"None logged\"}\n        </span>\n      </div>\n      {model.moments.length ? (\n        <ul className=\"-mx-2.5 mt-1.5 flex min-h-0 flex-col overflow-y-auto p-0.5 pb-3 [mask-image:linear-gradient(to_bottom,black_calc(100%-1.25rem),transparent)] [scrollbar-width:thin]\">\n          {model.moments.map((m) => {\n            const isOpen = handlers.openId === m.id;\n            return (\n              <li key={m.id}>\n                <button\n                  aria-controls={isOpen ? cardId : undefined}\n                  aria-expanded={isOpen}\n                  className={cn(\n                    \"grid w-full cursor-pointer grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-3 rounded-lg px-2 py-1 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring [@media(hover:hover)]:hover:bg-accent/60\",\n                    pressable,\n                    isOpen && \"bg-accent [@media(hover:hover)]:hover:bg-accent\",\n                  )}\n                  onBlur={() => handlers.onFocus(null)}\n                  onClick={() => handlers.onToggle(m.id)}\n                  onFocus={() => handlers.onFocus(m.id)}\n                  onPointerEnter={(e) => e.pointerType === \"mouse\" && handlers.onHover(m.id)}\n                  onPointerLeave={() => handlers.onHover(null)}\n                  type=\"button\"\n                >\n                  <KindIcon className=\"size-6 [&_svg]:size-3\" kind={m.kind} />\n                  <span className=\"min-w-0\">\n                    <span className=\"block truncate\">{m.title}</span>\n                    <span className=\"block text-muted-foreground text-xs tabular-nums\">{momentDates(m)}</span>\n                  </span>\n                  {m.impact && <span className={cn(\"text-xs tabular-nums\", tone(m.impact.change))}>{percent(m.impact.change)}</span>}\n                </button>\n              </li>\n            );\n          })}\n        </ul>\n      ) : (\n        <p className=\"mt-2 text-pretty text-muted-foreground text-xs\">Nothing happened worth pinning in this range. Add a moment to see it on the line.</p>\n      )}\n    </section>\n  );\n}\n\nconst NAV: { label: string; icon: LucideIcon }[] = [\n  { label: \"Home\", icon: HouseIcon },\n  { label: \"Orders\", icon: ShoppingBagIcon },\n  { label: \"Products\", icon: PackageIcon },\n  { label: \"Customers\", icon: UsersIcon },\n  { label: \"Revenue\", icon: ChartSplineIcon },\n];\n\nfunction RailButton({ label, active, icon: Icon, onClick }: { label: string; active?: boolean; icon: LucideIcon; onClick?: () => void }) {\n  return (\n    <Tooltip>\n      <TooltipTrigger\n        render={\n          <button\n            aria-current={active ? \"page\" : undefined}\n            aria-label={label}\n            className={cn(\n              \"flex size-9 cursor-pointer items-center justify-center rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-ring\",\n              pressable,\n              active ? \"bg-accent text-foreground\" : \"text-muted-foreground [@media(hover:hover)]:hover:bg-accent/60 [@media(hover:hover)]:hover:text-foreground\",\n            )}\n            onClick={onClick}\n            type=\"button\"\n          />\n        }\n      >\n        <Icon aria-hidden className=\"size-4\" />\n      </TooltipTrigger>\n      <TooltipPopup side=\"right\">{label}</TooltipPopup>\n    </Tooltip>\n  );\n}\n\nfunction SectionEmpty({ label, icon: Icon, onBack }: { label: string; icon: LucideIcon; onBack: () => void }) {\n  return (\n    <div className=\"flex min-h-0 flex-1 flex-col p-4 @3xl:p-7\">\n      <Empty className=\"flex-1 rounded-2xl border border-dashed\">\n        <EmptyHeader>\n          <EmptyMedia variant=\"icon\">\n            <Icon />\n          </EmptyMedia>\n          <EmptyTitle className=\"font-semibold text-base\">{label} opens in its own view</EmptyTitle>\n          <EmptyDescription className=\"text-pretty\">This preview only includes the revenue story.</EmptyDescription>\n        </EmptyHeader>\n        <EmptyContent>\n          <Button className={pressable} onClick={onBack} size=\"sm\" variant=\"outline\">\n            Back to revenue\n          </Button>\n        </EmptyContent>\n      </Empty>\n    </div>\n  );\n}\n\nexport function RevenueStory({\n  days = SAMPLE_DAYS,\n  channels = SAMPLE_CHANNELS,\n  moments = SAMPLE_MOMENTS,\n  store = { name: \"Fernwood Goods\", plan: \"Growth plan\" },\n  user = { name: \"Ines Moreau\", email: \"ines@fernwood.shop\" },\n  defaultRange = \"30d\",\n  onRangeChange,\n  onNavigate,\n  className,\n}: RevenueStoryProps) {\n  const cardId = useId();\n  const [range, setRange] = useState<RangeKey>(defaultRange);\n  const [nav, setNav] = useState(\"Revenue\");\n  const [hoverId, setHoverId] = useState<string | null>(null);\n  const [focusId, setFocusId] = useState<string | null>(null);\n  const [pinnedId, setPinnedId] = useState<string | null>(null);\n  const [status, setStatus] = useState<string | null>(null);\n\n  const dayIndex = useMemo(() => new Map(days.map((d, i) => [d.date, i])), [days]);\n  const impacts = useMemo(\n    () => new Map(moments.map((m) => [m.id, impactOf(m, days, dayIndex, channels)])),\n    [moments, days, dayIndex, channels],\n  );\n  const model = useMemo(() => buildModel(days, channels, moments, dayIndex, impacts, range), [days, channels, moments, dayIndex, impacts, range]);\n  const openId = hoverId ?? focusId ?? pinnedId;\n\n  useEffect(() => {\n    if (!status) return;\n    const timer = window.setTimeout(() => setStatus(null), 2200);\n    return () => window.clearTimeout(timer);\n  }, [status]);\n\n  const handlers: MomentHandlers = {\n    openId: model.moments.some((m) => m.id === openId) ? openId : null,\n    pinnedId,\n    onHover: setHoverId,\n    onFocus: setFocusId,\n    onToggle: (id) => setPinnedId((p) => (p === id ? null : id)),\n  };\n\n  const changeRange = (next: RangeKey) => {\n    setRange(next);\n    setPinnedId(null);\n    onRangeChange?.(next);\n  };\n\n  const go = (label: string) => {\n    setNav(label);\n    onNavigate?.(label);\n  };\n\n  const summaryText = () => {\n    const change = model.prevTotal === null ? null : model.total - model.prevTotal;\n    const period = `${dayLabel(model.start)} – ${dayLabel(model.end)}, ${yearOf(model.end)}`;\n    return `${store.name} revenue, ${period}: ${money(model.total)}${change === null ? \"\" : `, ${change < 0 ? \"down\" : \"up\"} ${compact(change)} on the previous period`}.`;\n  };\n\n  const downloadCsv = () => {\n    const header = model.step === 7 ? \"week_starting,revenue,previous\" : \"date,revenue,previous\";\n    const lines = model.buckets.map((b) => `${isoOf(b.t)},${Math.round(b.value)},${b.prev === null ? \"\" : Math.round(b.prev)}`);\n    const url = URL.createObjectURL(new Blob([[header, ...lines].join(\"\\n\")], { type: \"text/csv\" }));\n    const a = document.createElement(\"a\");\n    a.href = url;\n    a.download = `revenue-${model.range}.csv`;\n    a.click();\n    URL.revokeObjectURL(url);\n    setStatus(\"CSV downloaded\");\n  };\n\n  const copySummary = () => {\n    navigator.clipboard?.writeText(summaryText()).then(\n      () => setStatus(\"Summary copied\"),\n      () => setStatus(\"Couldn't copy\"),\n    );\n  };\n\n  const initials = user.name\n    .split(\" \")\n    .map((p) => p[0])\n    .join(\"\")\n    .slice(0, 2);\n  const section = NAV.find((item) => item.label === nav) ?? NAV[4];\n  const rangeLong = RANGES.find((r) => r.value === range)?.long ?? \"\";\n\n  return (\n    <TooltipProvider>\n      <div className={cn(\"@container relative isolate flex h-[760px] w-full overflow-hidden bg-background text-foreground text-sm\", className)}>\n        <aside aria-label=\"App\" className=\"hidden w-14 shrink-0 flex-col items-center gap-1 border-r bg-muted/40 py-3 @3xl:flex\">\n          <span\n            aria-label={store.name}\n            className=\"mb-3 flex size-8 items-center justify-center rounded-lg bg-primary font-heading font-semibold text-primary-foreground text-sm\"\n            role=\"img\"\n          >\n            {store.name[0]}\n          </span>\n          <nav aria-label=\"Main\" className=\"flex flex-col gap-1\">\n            {NAV.map((item) => (\n              <RailButton active={item.label === nav} icon={item.icon} key={item.label} label={item.label} onClick={() => go(item.label)} />\n            ))}\n          </nav>\n          <div className=\"mt-auto flex flex-col items-center gap-2\">\n            <RailButton icon={SettingsIcon} label=\"Settings\" />\n            <Avatar aria-label={user.name} className=\"size-7\">\n              <AvatarFallback className=\"text-[11px]\">{initials}</AvatarFallback>\n            </Avatar>\n          </div>\n        </aside>\n\n        <div className=\"flex min-w-0 flex-1 flex-col\">\n          <header className=\"flex h-12 shrink-0 items-center gap-3 border-b px-4 @3xl:px-7\">\n            <span\n              aria-hidden\n              className=\"flex size-6 items-center justify-center rounded-md bg-primary font-heading font-semibold text-primary-foreground text-xs @3xl:hidden\"\n            >\n              {store.name[0]}\n            </span>\n            <nav aria-label=\"Breadcrumb\" className=\"flex min-w-0 flex-1 items-center gap-1.5 text-sm\">\n              <span className=\"hidden truncate text-muted-foreground @md:inline\">{store.name}</span>\n              <ChevronRightIcon aria-hidden className=\"hidden size-3.5 shrink-0 text-muted-foreground/70 @md:block\" />\n              <span aria-current=\"page\" className=\"truncate font-medium\">\n                {section.label}\n              </span>\n            </nav>\n            <span aria-live=\"polite\" className=\"hidden text-muted-foreground text-xs @2xl:inline\">\n              {status ?? \"Updated 2 min ago\"}\n            </span>\n            {section.label === \"Revenue\" && (\n              <Menu>\n                <MenuTrigger render={<Button className={pressable} size=\"sm\" variant=\"outline\" />}>\n                  <DownloadIcon />\n                  Export\n                  <ChevronDownIcon className=\"-me-0.5 opacity-60\" />\n                </MenuTrigger>\n                <MenuPopup align=\"end\" className=\"min-w-48\">\n                  <MenuItem onClick={copySummary}>\n                    <ClipboardIcon />\n                    Copy summary\n                  </MenuItem>\n                  <MenuItem onClick={downloadCsv}>\n                    <DownloadIcon />\n                    Download CSV\n                  </MenuItem>\n                </MenuPopup>\n              </Menu>\n            )}\n          </header>\n\n          {section.label !== \"Revenue\" ? (\n            <SectionEmpty icon={section.icon} label={section.label} onBack={() => go(\"Revenue\")} />\n          ) : (\n            <main className=\"min-h-0 flex-1 overflow-y-auto\">\n              <div className=\"@container mx-auto flex min-h-full max-w-[1280px] flex-col @5xl:h-full gap-5 px-4 pt-5 pb-6 @3xl:px-7 @3xl:pt-6\">\n                <div className=\"flex flex-col gap-3\">\n                  <div className=\"flex flex-wrap items-center justify-between gap-x-4 gap-y-3\">\n                    <p className=\"text-muted-foreground text-xs tabular-nums\">\n                      <span className=\"font-medium text-foreground\">{rangeLong}</span> · {dayLabel(model.start, yearOf(model.end))} – {dayLabel(model.end)}\n                      {model.prevStart !== null && model.prevEnd !== null && (\n                        <span className=\"hidden @md:inline\">\n                          {\" \"}\n                          vs {dayLabel(model.prevStart, yearOf(model.end))} – {dayLabel(model.prevEnd, yearOf(model.end))}\n                        </span>\n                      )}\n                    </p>\n                    <RangeSwitch onChange={changeRange} value={range} />\n                  </div>\n                  <Summary model={model} />\n                </div>\n\n                <div className=\"grid min-h-0 flex-1 grid-cols-1 gap-x-7 gap-y-8 @4xl:grid-cols-[minmax(0,1fr)_20rem] @4xl:grid-rows-[minmax(0,1fr)]\">\n                  <StoryChart cardId={cardId} handlers={handlers} model={model} />\n                  <div className=\"flex min-h-0 min-w-0 flex-col gap-5 border-t pt-6 @4xl:border-t-0 @4xl:border-l @4xl:pt-0 @4xl:ps-7\">\n                    <Breakdown model={model} />\n                    <MomentList cardId={cardId} handlers={handlers} model={model} />\n                  </div>\n                </div>\n              </div>\n            </main>\n          )}\n        </div>\n      </div>\n    </TooltipProvider>\n  );\n}\n"
    }
  ]
}