{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "flavour-carousel",
  "title": "Flavour Carousel",
  "author": "AlgorizeTech",
  "description": "A product hero for anything that comes in flavours: the product stands in a mountain of powder against a moss backdrop and its flavours flank it on four tilted cream tiles. It rises from behind the powder spinning and settles; then every five seconds, or on a click, the chosen tile slides into the cup and the cup cross-fades to that flavour without moving; a glow takes the flavour's colour, a price pill and add-to-cart hang under the cup. One component for both themes: in dark mode the tiles go translucent black.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "https://avaraui.com/r/button.json",
    "utils"
  ],
  "files": [
    {
      "path": "src/components/custom/blocks/FlavourCarouselBlock.tsx",
      "content": "\"use client\";\n\nimport React, {\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n  useSyncExternalStore,\n} from \"react\";\nimport { ShoppingCart } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\nimport Button from \"./Button\";\nimport { cubicBezier } from \"./motion-curves\";\n\n// ==========================================\n// FLAVOUR CAROUSEL\n// A product hero for anything that comes in flavours — a matcha latte here,\n// but ice cream, juice, a candle: the product stands in a mountain of matcha\n// powder against a moss-green backdrop and the flavours flank it on four\n// tilted cream tiles. Every five seconds, or when a tile is clicked, the ring\n// turns: the chosen tile slides into the cup and shrinks away, and the cup —\n// which never moves — cross-fades to the picture with that flavour inside. A\n// soft glow behind the cup takes the flavour's colour; a price pill and an\n// add-to-cart button hang under the cup and the headline sits low over the\n// powder. The powder is a transparent cutout laid in front of the cup, so\n// the glass stands in it. When the section first appears only the cup is\n// there; the ring rises from behind the powder spinning fast, slows over a\n// couple of seconds into its resting places, and then the ordinary turns\n// begin. Without pictures the scene is drawn: moss with a\n// heap of powder. The scene is the same in both themes; in dark mode only the\n// tiles change, from cream to a translucent black that sits into the ground.\n// Positions are fractions of the stage, measured from the design at 733 × 426.\n// ==========================================\n\nexport interface Flavour {\n  name: string;\n  /** Shown beside the name on the tag, e.g. \"$6.50\". */\n  price?: string;\n  /** The flavour's colour: the glow behind the product. */\n  tint?: string;\n  /** The product with this flavour inside. Every product image must share the same crop so only the contents appear to change. */\n  product: string;\n  /** The ingredient on the tile. */\n  tile: string;\n  /** Alt text for the product image; defaults to the name. */\n  alt?: string;\n}\n\nexport interface FlavourCarouselProps extends Omit<React.HTMLAttributes<HTMLElement>, \"onChange\"> {\n  flavours: Flavour[];\n  /** The headline over the mound. */\n  heading?: React.ReactNode;\n  /** Index of the flavour in the cup at the start. */\n  initial?: number;\n  /** Milliseconds between turns; `0` turns autoplay off. */\n  interval?: number;\n  onChange?: (index: number, flavour: Flavour) => void;\n  /** The add-to-cart button; leave `onAdd` out to hide it. */\n  onAdd?: (flavour: Flavour, index: number) => void;\n  addLabel?: string;\n  /** The backdrop, covering the section. Without one the ground is drawn from `background`. */\n  backgroundImage?: string;\n  /** object-position for the backdrop. */\n  backgroundPosition?: string;\n  /**\n   * The powder: a transparent cutout, anchored to the foot of the stage and\n   * laid in front of the cup so the glass stands in it. Its peak should be at\n   * the picture's horizontal centre.\n   */\n  foregroundImage?: string;\n  /** The powder's height as a share of the stage; wider than the stage is clipped. */\n  foregroundHeight?: number;\n  /**\n   * The entrance: the ring rises from behind the powder, spinning, and settles.\n   * `in-view` plays it the first time the section is on screen, `immediate`\n   * at once, `none` renders the ring in place. Reduced motion skips it.\n   */\n  reveal?: \"in-view\" | \"immediate\" | \"none\";\n  /** The ground when there is no backdrop. */\n  background?: string;\n  /** The drawn powder mound, as [light, dark]. */\n  mound?: [string, string];\n  /** The cream of the tiles (light mode), the pill and the cart. */\n  paper?: string;\n}\n\n// ------------------------------------------\n// The ring. Each tile's resting place is a function of its distance from the\n// chosen one: the chosen tile is inside the cup (small, invisible, up at the\n// rim); its neighbours flank the cup; the next pair sit lower, smaller and\n// more tilted; anything further waits out of sight past the edge. `x` is a\n// fraction of the stage width and `y` of its height, so the composition holds\n// at any size.\n// ------------------------------------------\ninterface Slot {\n  x: number;\n  y: number;\n  scale: number;\n  rotate: number;\n  opacity: number;\n  z: number;\n}\n\nconst SLOTS: Record<number, Slot> = {\n  0: { x: 0, y: -0.18, scale: 0.28, rotate: 0, opacity: 0, z: 1 },\n  1: { x: 0.233, y: 0, scale: 1, rotate: 8, opacity: 1, z: 4 },\n  2: { x: 0.42, y: 0.135, scale: 0.9, rotate: 12, opacity: 1, z: 3 },\n  3: { x: 0.6, y: 0.28, scale: 0.7, rotate: 20, opacity: 0, z: 2 },\n};\n\n// On phones only the nearest pair is on screen; the rest queue past the edge.\nconst SLOTS_COMPACT: Record<number, Slot> = {\n  0: SLOTS[0],\n  1: { x: 0.35, y: 0.02, scale: 1, rotate: 9, opacity: 1, z: 4 },\n  2: { x: 0.62, y: 0.12, scale: 0.6, rotate: 20, opacity: 0, z: 3 },\n  3: { x: 0.8, y: 0.2, scale: 0.5, rotate: 26, opacity: 0, z: 2 },\n};\n\nfunction slotFor(rel: number, compact: boolean): Slot {\n  const table = compact ? SLOTS_COMPACT : SLOTS;\n  const d = Math.min(Math.abs(rel), 3);\n  const s = table[d];\n  const sign = Math.sign(rel);\n  return { ...s, x: s.x * sign, rotate: s.rotate * sign };\n}\n\n/** Signed distance from `active` to `i` around a ring of `n`, in [-n/2, n/2). */\nfunction ringDistance(i: number, active: number, n: number) {\n  let d = (i - active) % n;\n  if (d < 0) d += n;\n  if (d >= n / 2) d -= n;\n  return d;\n}\n\ninterface Spring {\n  stiffness: number;\n  damping: number;\n  mass: number;\n}\n\nconst SPRING: Spring = { stiffness: 150, damping: 24, mass: 1 };\n// Walking to a tile two steps away: one step at a time, at about twice the pace.\nconst QUICK_SPRING: Spring = { stiffness: 340, damping: 32, mass: 1 };\nconst STEP_BEAT = 230;\n// The entrance spin: one lap plus two, as one continuous turn that starts\n// fast and eases to a stop in a little over two seconds.\nconst INTRO_EXTRA_STEPS = 2;\nconst INTRO_DURATION = 2400;\nconst INTRO_DELAY = 150;\nconst INTRO_EASE = cubicBezier(0.2, 0.85, 0.2, 1);\n\n/** Signed, fractional distance from `phase` to `i` around the ring — the ring mid-turn. */\nfunction ringDistanceAt(i: number, phase: number, n: number) {\n  let d = (i - phase) % n;\n  if (d < 0) d += n;\n  if (d >= n / 2) d -= n;\n  return d;\n}\n\n/** The slot for a fractional distance: a blend of the two slots either side of it. */\nfunction slotAt(rel: number, compact: boolean): Slot {\n  const table = compact ? SLOTS_COMPACT : SLOTS;\n  const a = Math.min(Math.abs(rel), 3);\n  const lo = Math.floor(a);\n  const hi = Math.min(lo + 1, 3);\n  const t = a - lo;\n  const A = table[lo];\n  const B = table[hi];\n  const mix = (p: number, q: number) => p + (q - p) * t;\n  const sign = Math.sign(rel) || 1;\n  return {\n    x: mix(A.x, B.x) * sign,\n    y: mix(A.y, B.y),\n    scale: mix(A.scale, B.scale),\n    rotate: mix(A.rotate, B.rotate) * sign,\n    opacity: mix(A.opacity, B.opacity),\n    z: t < 0.5 ? A.z : B.z,\n  };\n}\nconst EASE_OUT = \"cubic-bezier(0.22, 1, 0.36, 1)\";\n// A plain `{ duration }` eases out.\nconst EASE_OUT_DEFAULT = \"cubic-bezier(0, 0, 0.58, 1)\";\n\nconst keyframes = `\n@keyframes flavour-carousel-price-in { from { translate: 0 12px; opacity: 0; filter: blur(3px); } }\n`;\n\n// ------------------------------------------\n// Motion without a library.\n// ------------------------------------------\nconst REDUCED_MOTION = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribeReducedMotion(onChange: () => void) {\n  const query = window.matchMedia(REDUCED_MOTION);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n}\n\nfunction usePrefersReducedMotion() {\n  return useSyncExternalStore(\n    subscribeReducedMotion,\n    () => window.matchMedia(REDUCED_MOTION).matches,\n    () => false,\n  );\n}\n\n/** A number that can be watched: the ring's phase during the entrance. */\ninterface Phase {\n  get: () => number;\n  set: (value: number) => void;\n  on: (listener: (value: number) => void) => () => void;\n}\n\nfunction createPhase(initial: number): Phase {\n  let value = initial;\n  const listeners = new Set<(value: number) => void>();\n  return {\n    get: () => value,\n    set(next) {\n      value = next;\n      listeners.forEach((listener) => listener(next));\n    },\n    on(listener) {\n      listeners.add(listener);\n      return () => {\n        listeners.delete(listener);\n      };\n    },\n  };\n}\n\n/**\n * Where a spring released at `from` with `velocity` (units per second)\n * towards `to` is after `t` seconds — the closed form Motion's spring\n * uses, so a spring picked up mid-flight keeps its speed.\n */\nfunction springPosition(spring: Spring, from: number, to: number, velocity: number, t: number) {\n  const { stiffness, damping, mass } = spring;\n  const zeta = damping / (2 * Math.sqrt(stiffness * mass));\n  const omega0 = Math.sqrt(stiffness / mass);\n  const delta = to - from;\n  const envelope = Math.exp(-zeta * omega0 * t);\n  if (zeta < 1) {\n    const omegaD = omega0 * Math.sqrt(1 - zeta * zeta);\n    return (\n      to -\n      envelope *\n        (((-velocity + zeta * omega0 * delta) / omegaD) * Math.sin(omegaD * t) + delta * Math.cos(omegaD * t))\n    );\n  }\n  if (zeta === 1) return to - Math.exp(-omega0 * t) * (delta + (-velocity + omega0 * delta) * t);\n  const omegaD = omega0 * Math.sqrt(zeta * zeta - 1);\n  const f = Math.min(omegaD * t, 300);\n  return to - (envelope * ((-velocity + zeta * omega0 * delta) * Math.sinh(f) + omegaD * delta * Math.cosh(f))) / omegaD;\n}\n\nconst TILE_KEYS = [\"x\", \"y\", \"scale\", \"rotate\", \"opacity\"] as const;\ntype TileValues = Record<(typeof TILE_KEYS)[number], number>;\n\ninterface Channel {\n  value: number;\n  from: number;\n  to: number;\n  velocity: number;\n  start: number;\n  spring: Spring | null;\n}\n\n/**\n * A tile's five values, each animated by its own spring. Retargeting a value\n * mid-flight starts the new spring from where it is at the speed it has,\n * and a `null` spring jumps. `render` receives every frame, with the element\n * handed to `attach` (frames before there is one are skipped).\n */\nfunction createTileMotion<E extends HTMLElement>(\n  initial: TileValues,\n  render: (el: E, values: TileValues) => void,\n) {\n  const channels = {} as Record<keyof TileValues, Channel>;\n  let element: E | null = null;\n  const draw = () => {\n    if (element) render(element, values());\n  };\n  for (const key of TILE_KEYS) {\n    const value = initial[key];\n    channels[key] = { value, from: value, to: value, velocity: 0, start: 0, spring: null };\n  }\n  let frame = 0;\n\n  const values = () => {\n    const out = {} as TileValues;\n    for (const key of TILE_KEYS) out[key] = channels[key].value;\n    return out;\n  };\n  const at = (c: Channel, t: number) => springPosition(c.spring!, c.from, c.to, c.velocity, Math.max(t, 0));\n  const speedAt = (c: Channel, t: number) => (at(c, t + 0.0005) - at(c, t - 0.0005)) / 0.001;\n\n  const tick = (now: number) => {\n    frame = 0;\n    let moving = false;\n    for (const key of TILE_KEYS) {\n      const c = channels[key];\n      if (!c.spring) continue;\n      const t = (now - c.start) / 1000;\n      const value = at(c, t);\n      // Settled once close and slow enough, by the same thresholds as Motion.\n      const granular = Math.abs(c.to - c.from) < 5;\n      const restDelta = granular ? 0.005 : 0.5;\n      const restSpeed = granular ? 0.01 : 2;\n      const underdamped = c.spring.damping < 2 * Math.sqrt(c.spring.stiffness * c.spring.mass);\n      if (Math.abs(c.to - value) <= restDelta && (!underdamped || Math.abs(speedAt(c, t)) <= restSpeed)) {\n        c.value = c.to;\n        c.spring = null;\n      } else {\n        c.value = value;\n        moving = true;\n      }\n    }\n    draw();\n    if (moving) frame = requestAnimationFrame(tick);\n  };\n\n  return {\n    values,\n    /** The element the frames are written to: a callback ref. */\n    attach(el: E | null) {\n      element = el;\n    },\n    to(target: TileValues, spring: Spring | null) {\n      const now = performance.now();\n      let jumped = false;\n      let started = false;\n      for (const key of TILE_KEYS) {\n        const c = channels[key];\n        if (c.to === target[key]) continue;\n        if (!spring) {\n          c.value = c.from = c.to = target[key];\n          c.velocity = 0;\n          c.spring = null;\n          jumped = true;\n          continue;\n        }\n        let velocity = 0;\n        if (c.spring) {\n          const t = (now - c.start) / 1000;\n          c.value = at(c, t);\n          velocity = speedAt(c, t);\n        }\n        c.from = c.value;\n        c.to = target[key];\n        c.velocity = velocity;\n        c.start = now;\n        c.spring = spring;\n        started = true;\n      }\n      if (jumped) draw();\n      if (started && !frame) frame = requestAnimationFrame(tick);\n    },\n    jump(target: TileValues) {\n      for (const key of TILE_KEYS) {\n        const c = channels[key];\n        c.value = c.from = c.to = target[key];\n        c.velocity = 0;\n        c.spring = null;\n      }\n      draw();\n    },\n    stop() {\n      cancelAnimationFrame(frame);\n      frame = 0;\n    },\n  };\n}\n\nfunction tileTransform({ x, y, scale, rotate }: TileValues) {\n  return `translateX(${x}px) translateY(${y}px) scale(${scale}) rotate(${rotate}deg)`;\n}\n\n// ------------------------------------------\n// The mound: two soft heaps of powder, the lighter one behind, the darker in\n// front, given a fine grain by a turbulence filter so it reads as powder and\n// not as plastic.\n// ------------------------------------------\nfunction Mound({ light, dark, id }: { light: string; dark: string; id: string }) {\n  return (\n    <svg\n      aria-hidden\n      viewBox=\"0 0 1200 320\"\n      preserveAspectRatio=\"xMidYMax slice\"\n      className=\"pointer-events-none absolute inset-x-0 bottom-0 h-[46%] w-full\"\n    >\n      <defs>\n        <filter id={`${id}-grain`} x=\"0\" y=\"0\" width=\"100%\" height=\"100%\">\n          <feTurbulence type=\"fractalNoise\" baseFrequency=\"0.9\" numOctaves=\"2\" seed=\"7\" result=\"noise\" />\n          <feColorMatrix in=\"noise\" type=\"matrix\" values=\"0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 0.18 0\" result=\"grain\" />\n          {/* Keep the grain inside the heaps, or it prints as a grey box over the scene. */}\n          <feComposite in=\"grain\" in2=\"SourceGraphic\" operator=\"in\" result=\"grainIn\" />\n          <feBlend in=\"SourceGraphic\" in2=\"grainIn\" mode=\"multiply\" />\n        </filter>\n        <linearGradient id={`${id}-back`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n          <stop offset=\"0\" stopColor={light} />\n          <stop offset=\"1\" stopColor={dark} />\n        </linearGradient>\n        <linearGradient id={`${id}-front`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n          <stop offset=\"0\" stopColor={light} stopOpacity=\"0.95\" />\n          <stop offset=\"0.55\" stopColor={dark} />\n          <stop offset=\"1\" stopColor={dark} />\n        </linearGradient>\n      </defs>\n      <g filter={`url(#${id}-grain)`}>\n        <path\n          fill={`url(#${id}-back)`}\n          d=\"M-40 320 C 90 296, 190 262, 300 214 C 380 180, 430 172, 480 132 C 530 92, 570 66, 604 60 C 640 66, 690 108, 740 134 C 800 164, 840 160, 900 192 C 980 232, 1090 284, 1240 320 Z\"\n        />\n        <path\n          fill={`url(#${id}-front)`}\n          d=\"M-40 320 C 110 312, 220 286, 320 246 C 400 214, 460 176, 540 156 C 600 142, 650 170, 720 196 C 790 222, 850 208, 930 232 C 1010 256, 1120 300, 1240 320 Z\"\n        />\n      </g>\n    </svg>\n  );\n}\n\n// ------------------------------------------\n// A tile. Its position lives outside React: during the entrance it follows\n// the ring's phase every frame (no re-render), and once the ring has landed\n// the ordinary springs animate the very same values, so the handover is\n// seamless.\n// ------------------------------------------\nfunction Tile({\n  flavour,\n  index,\n  n,\n  rel,\n  slot,\n  from,\n  size,\n  width,\n  height,\n  compact,\n  phase,\n  spinning,\n  transition,\n  reduce,\n  onChoose,\n}: {\n  flavour: Flavour;\n  index: number;\n  n: number;\n  rel: number;\n  slot: Slot;\n  /** Where a remounted tile starts: the hidden slot on its new side. */\n  from: Slot | null;\n  size: number;\n  width: number;\n  height: number;\n  compact: boolean;\n  phase: Phase;\n  spinning: boolean;\n  /** The spring for the next move; `null` jumps. */\n  transition: Spring | null;\n  reduce: boolean;\n  onChoose: (index: number) => void;\n}) {\n  const [{ motion, attach, initialStyle }] = useState(() => {\n    const start = from ?? slot;\n    const tileMotion = createTileMotion<HTMLButtonElement>(\n      { x: start.x * width, y: start.y * height, scale: start.scale, rotate: start.rotate, opacity: start.opacity },\n      (el, v) => {\n        el.style.transform = tileTransform(v);\n        el.style.opacity = String(v.opacity);\n      },\n    );\n    // Where the tile is drawn before any frame has run; after that the values\n    // are written straight to the element (the button, via `attach`).\n    const v = tileMotion.values();\n    return {\n      motion: tileMotion,\n      attach: tileMotion.attach,\n      initialStyle: { transform: tileTransform(v), opacity: v.opacity },\n    };\n  });\n  useEffect(() => () => motion.stop(), [motion]);\n\n  // Hover lifts and straightens the tile, a press sinks it — both on the\n  // tile's own spring, and not while the ring is spinning or motion is reduced.\n  const gestures = !(reduce || spinning);\n  const [hovered, setHovered] = useState(false);\n  const [pressed, setPressed] = useState(false);\n  const hoverOn = gestures && hovered;\n  const pressOn = gestures && pressed;\n\n  useEffect(() => {\n    if (!pressed) return;\n    const release = () => setPressed(false);\n    window.addEventListener(\"pointerup\", release);\n    window.addEventListener(\"pointercancel\", release);\n    return () => {\n      window.removeEventListener(\"pointerup\", release);\n      window.removeEventListener(\"pointercancel\", release);\n    };\n  }, [pressed]);\n\n  useLayoutEffect(() => {\n    if (!spinning) return;\n    const apply = (p: number) => {\n      const s = slotAt(ringDistanceAt(index, p, n), compact);\n      motion.jump({ x: s.x * width, y: s.y * height, scale: s.scale, rotate: s.rotate, opacity: s.opacity });\n    };\n    apply(phase.get());\n    return phase.on(apply);\n  }, [spinning, phase, index, n, compact, width, height, motion]);\n\n  const targetX = slot.x * width;\n  const targetY = slot.y * height;\n  const targetScale = slot.scale * (pressOn ? 0.96 : hoverOn ? 1.06 : 1);\n  const targetRotate = slot.rotate * (hoverOn ? 0.6 : 1);\n  const targetOpacity = slot.opacity;\n  useLayoutEffect(() => {\n    if (spinning) return;\n    motion.to(\n      { x: targetX, y: targetY, scale: targetScale, rotate: targetRotate, opacity: targetOpacity },\n      transition,\n    );\n  }, [spinning, targetX, targetY, targetScale, targetRotate, targetOpacity, transition, motion]);\n\n  return (\n    <button\n      ref={attach}\n      type=\"button\"\n      aria-label={rel === 0 ? `${flavour.name}, in the cup` : `Choose ${flavour.name}`}\n      aria-pressed={rel === 0}\n      tabIndex={rel === 0 ? -1 : 0}\n      onClick={() => onChoose(index)}\n      onPointerEnter={(e) => {\n        if (gestures && e.pointerType !== \"touch\") setHovered(true);\n      }}\n      onPointerLeave={() => setHovered(false)}\n      onPointerDown={(e) => {\n        if (gestures && e.isPrimary && (e.pointerType !== \"mouse\" || e.button === 0)) setPressed(true);\n      }}\n      onKeyDown={(e) => {\n        if (gestures && e.key === \"Enter\" && !e.repeat) setPressed(true);\n      }}\n      onKeyUp={(e) => {\n        if (e.key === \"Enter\") setPressed(false);\n      }}\n      onBlur={() => setPressed(false)}\n      style={{\n        ...initialStyle,\n        width: size,\n        height: size,\n        marginLeft: -size / 2,\n        marginTop: -size / 2,\n        zIndex: slot.z,\n        pointerEvents: slot.opacity === 0 || spinning ? \"none\" : \"auto\",\n      }}\n      className={cn(\n        // Its own compositing layer: rotated tiles otherwise show raster seams in Chrome.\n        \"group absolute left-1/2 top-[42%] cursor-pointer rounded-[14%] will-change-transform [backface-visibility:hidden]\",\n        // Cream tiles; in dark mode a translucent black that sits into the ground.\n        \"bg-[var(--fc-paper)] shadow-[0_30px_50px_-24px_rgba(0,0,0,0.7),inset_0_1px_0_rgba(255,255,255,0.9)]\",\n        \"dark:bg-black/40 dark:shadow-[0_30px_50px_-24px_rgba(0,0,0,0.8),inset_0_0_0_1px_rgba(255,255,255,0.08)] dark:backdrop-blur-sm\",\n        \"outline-none focus-visible:ring-4 focus-visible:ring-white/70\",\n      )}\n    >\n      <img\n        src={flavour.tile}\n        alt=\"\"\n        draggable={false}\n        className=\"pointer-events-none absolute inset-[11%] h-[78%] w-[78%] select-none object-contain drop-shadow-[0_10px_12px_rgba(0,0,0,0.25)]\"\n      />\n    </button>\n  );\n}\n\n// ------------------------------------------\n// The price ticker\n// ------------------------------------------\ninterface PillLayer {\n  key: number;\n  /** Rises in when it mounts (not the first one). */\n  enter: boolean;\n  /** Set while leaving: where it stood, so it can leave the flow in place. */\n  rect: { top: number; left: number; width: number; height: number } | null;\n}\n\nconst PRICE_EXIT = { translate: \"0px -12px\", opacity: \"0\", filter: \"blur(3px)\" };\nconst PRICE_REST = { translate: \"0px 0px\", opacity: \"1\", filter: \"blur(0px)\" };\n\n/** From the element's current computed values to `to`, as WAAPI keyframes. */\nfunction fromCurrent(el: Element, to: Record<string, string>) {\n  const style = getComputedStyle(el);\n  const frames: Record<string, string[]> = {};\n  for (const key of Object.keys(to)) frames[key] = [style.getPropertyValue(key), to[key]];\n  return frames;\n}\n\n// ------------------------------------------\n// Root\n// ------------------------------------------\nexport function FlavourCarousel({\n  flavours,\n  heading,\n  initial = 0,\n  interval = 5000,\n  onChange,\n  onAdd,\n  addLabel = \"Add to cart\",\n  backgroundImage,\n  backgroundPosition = \"50% 50%\",\n  foregroundImage,\n  foregroundHeight = 0.41,\n  reveal = \"in-view\",\n  background = \"#3b4726\",\n  mound = [\"#7a9550\", \"#465b2b\"],\n  paper = \"#f4f1e7\",\n  className,\n  style,\n  ...props\n}: FlavourCarouselProps) {\n  const n = flavours.length;\n  const id = useId().replace(/:/g, \"\");\n  const reduce = usePrefersReducedMotion();\n  const stageRef = useRef<HTMLDivElement>(null);\n  const initialIndex = Math.min(Math.max(initial, 0), Math.max(n - 1, 0));\n  // The entrance: the ring starts a lap behind and spins forward to `initial`.\n  const introSteps = n + INTRO_EXTRA_STEPS;\n  const [intro, setIntro] = useState(reveal !== \"none\" && n > 1);\n  const [inView, setInView] = useState(reveal === \"immediate\");\n  const [active, setActive] = useState(initialIndex);\n  // The ring's fractional position during the entrance: a lap behind, easing forward to `initial`.\n  const [phase] = useState(() => createPhase(initialIndex - introSteps));\n  const [width, setWidth] = useState(0);\n  const [height, setHeight] = useState(0);\n  const [held, setHeld] = useState(false);\n  const [hidden, setHidden] = useState(false);\n  const [visible, setVisible] = useState(true);\n  // Product layers stack by recency: the newest on top fades in over the one\n  // before it, so the cup itself never dips in opacity mid-change.\n  const shown = active;\n  const [order, setOrder] = useState<number[]>(() => [shown]);\n  const cupRef = useRef<HTMLDivElement>(null);\n  const fades = useRef(new Map<number, Animation>());\n  const first = useRef(true);\n  // Which side of the cup each tile lives on. A tile only ever leaves on its\n  // own side; when the ring brings it round to the other side it is remounted\n  // at that side's hidden slot (`gen` bumps its key) and springs in from\n  // there, so nothing is ever seen crossing the stage. Settled for each turn\n  // while rendering, against the turn they were last settled for.\n  const [ring, setRing] = useState(() => ({\n    active,\n    side: flavours.map((_, i) => Math.sign(ringDistance(i, active, n)) || 1),\n    gen: flavours.map(() => 0),\n  }));\n  if (ring.active !== active) {\n    const prev = ring.active;\n    const side = [...ring.side];\n    const remount: number[] = [];\n    flavours.forEach((_, i) => {\n      const before = ringDistance(i, prev, n);\n      const after = ringDistance(i, active, n);\n      if (after === 0) return;\n      const sign = Math.sign(after);\n      // Emerging from the cup, or already on this side: nothing to do.\n      if (before === 0 || side[i] === sign) {\n        side[i] = sign;\n        return;\n      }\n      // Bound for the other side. Out of sight there: stay hidden on this side.\n      if (Math.abs(after) >= 3) return;\n      // Coming into view there: switch sides off screen and spring in.\n      side[i] = sign;\n      remount.push(i);\n    });\n    setRing({\n      active,\n      side,\n      gen: remount.length ? ring.gen.map((v, i) => (remount.includes(i) ? v + 1 : v)) : ring.gen,\n    });\n  }\n\n  const compact = width > 0 && width < 560;\n  // Tile size as a share of the stage: generous on phones, calmer as the ring gets room.\n  const tile = width * (compact ? 0.26 : width < 1024 ? 0.19 : 0.177);\n  // The small pieces scale with the stage, not the viewport, so they hold in a docs frame.\n  const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));\n  const headingSize = clamp(width * 0.06, 24, 64);\n  const pillHeight = clamp(width * 0.033, 22, 34);\n  const pillFont = clamp(width * 0.015, 10.5, 15);\n  const cartSize = clamp(width * 0.057, 36, 60);\n  const current = flavours[shown];\n\n  // Measure the stage so tile offsets can be fractions of its width.\n  useEffect(() => {\n    const el = stageRef.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) => {\n      setWidth(entry.contentRect.width);\n      setHeight(entry.contentRect.height);\n    });\n    ro.observe(el);\n    const r = el.getBoundingClientRect();\n    setWidth(r.width);\n    setHeight(r.height);\n    return () => ro.disconnect();\n  }, []);\n\n  // Off screen the ring stands still.\n  useEffect(() => {\n    const el = stageRef.current;\n    if (!el || typeof IntersectionObserver === \"undefined\") return;\n    const io = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting), { threshold: 0.15 });\n    io.observe(el);\n    return () => io.disconnect();\n  }, []);\n\n  // A tile further than one step away is walked to, step by step, like a\n  // carousel — the near one goes into the cup first, then the next arrives.\n  const targetRef = useRef<number | null>(null);\n  const [walking, setWalking] = useState(false);\n\n  const choose = useCallback(\n    (index: number) => {\n      const next = ((index % n) + n) % n;\n      if (next === active) return;\n      const d = ringDistance(next, active, n);\n      if (Math.abs(d) <= 1) {\n        targetRef.current = null;\n        setWalking(false);\n        setActive(next);\n        return;\n      }\n      targetRef.current = next;\n      setWalking(true);\n      setActive((a) => (((a + Math.sign(d)) % n) + n) % n);\n    },\n    [n, active],\n  );\n\n  useEffect(() => {\n    const target = targetRef.current;\n    if (target === null) return;\n    if (active === target) {\n      targetRef.current = null;\n      // Let the last step finish at the quick pace before the springs relax.\n      const t = window.setTimeout(() => setWalking(false), STEP_BEAT);\n      return () => window.clearTimeout(t);\n    }\n    const dir = Math.sign(ringDistance(target, active, n));\n    const t = window.setTimeout(() => setActive((a) => (((a + dir) % n) + n) % n), STEP_BEAT);\n    return () => window.clearTimeout(t);\n  }, [active, n]);\n\n  // Once seen, in view for good.\n  if (visible && !inView) setInView(true);\n\n  // The entrance spin: one continuous turn of the phase, fast then easing to\n  // a stop on `initial`; when it lands the springs take over from exactly\n  // where it left the tiles.\n  // Reduced motion skips it: the ring is simply in place.\n  if (intro && inView && reduce) setIntro(false);\n  useEffect(() => {\n    if (!intro || !inView || reduce) return;\n    const from = phase.get();\n    let frame = 0;\n    let startTime = 0;\n    const tick = (now: number) => {\n      if (!startTime) startTime = now;\n      const elapsed = now - startTime - INTRO_DELAY;\n      if (elapsed >= 0) {\n        const t = Math.min(elapsed / INTRO_DURATION, 1);\n        phase.set(from + (initialIndex - from) * INTRO_EASE(t));\n        if (t === 1) {\n          setIntro(false);\n          return;\n        }\n      }\n      frame = requestAnimationFrame(tick);\n    };\n    frame = requestAnimationFrame(tick);\n    return () => cancelAnimationFrame(frame);\n  }, [intro, inView, reduce, phase, initialIndex]);\n\n  // When the cup's flavour changes, bring its picture to the top (while\n  // rendering, against the flavour last stacked)...\n  const [stacked, setStacked] = useState(shown);\n  if (stacked !== shown) {\n    setStacked(shown);\n    setOrder((prev) => [...prev.filter((i) => i !== shown), shown]);\n  }\n  // ...and, before that frame is painted, fade it in over the previous one.\n  const fadedRef = useRef(shown);\n  useLayoutEffect(() => {\n    if (fadedRef.current === shown) return;\n    fadedRef.current = shown;\n    const layer = cupRef.current?.querySelector<HTMLElement>(`[data-fc-product=\"${shown}\"]`);\n    if (!layer || reduce) return;\n    // A fade still running under the new top layer finishes on its own, so\n    // the pictures beneath always end up whole.\n    fades.current.get(shown)?.cancel();\n    const fade = layer.animate({ opacity: [0, 1] }, { duration: 900, easing: EASE_OUT });\n    fades.current.set(shown, fade);\n    fade.onfinish = () => {\n      if (fades.current.get(shown) === fade) fades.current.delete(shown);\n    };\n  }, [shown, reduce]);\n\n  // Report each change (not the first flavour) to the latest `onChange`.\n  const onChangeRef = useRef(onChange);\n  const flavoursRef = useRef(flavours);\n  useEffect(() => {\n    onChangeRef.current = onChange;\n    flavoursRef.current = flavours;\n  });\n  useEffect(() => {\n    if (first.current) {\n      first.current = false;\n      return;\n    }\n    onChangeRef.current?.(shown, flavoursRef.current[shown]);\n  }, [shown]);\n\n  useEffect(() => {\n    const running = fades.current;\n    return () => running.forEach((fade) => fade.cancel());\n  }, []);\n\n  // The price swaps like a ticker: the old one lifts out, taken out of the\n  // flow where it stood, while the new one rises in and sets the pill's width.\n  const [pill, setPill] = useState<PillLayer[]>(() => [{ key: shown, enter: false, rect: null }]);\n  const pillRefs = useRef(new Map<number, HTMLDivElement>());\n  const pillExits = useRef(new Map<number, Animation>());\n  const pillShownRef = useRef(shown);\n  // Under reduced motion the price just swaps: done while rendering, against\n  // the flavour the pill last showed.\n  const [pillFor, setPillFor] = useState(shown);\n  if (pillFor !== shown) {\n    setPillFor(shown);\n    if (reduce) setPill([{ key: shown, enter: false, rect: null }]);\n  }\n  useLayoutEffect(() => {\n    const prev = pillShownRef.current;\n    pillShownRef.current = shown;\n    if (prev === shown) return;\n    const exits = pillExits.current;\n    if (reduce) {\n      exits.forEach((exit) => exit.cancel());\n      exits.clear();\n      return;\n    }\n    // Leaving: freeze where it stands and lift it out from wherever it is.\n    const leaving = pillRefs.current.get(prev);\n    const rect = leaving\n      ? { top: leaving.offsetTop, left: leaving.offsetLeft, width: leaving.offsetWidth, height: leaving.offsetHeight }\n      : null;\n    if (leaving) {\n      exits.get(prev)?.cancel();\n      const exit = leaving.animate(fromCurrent(leaving, PRICE_EXIT), {\n        duration: 400,\n        easing: EASE_OUT,\n        fill: \"forwards\",\n      });\n      exits.set(prev, exit);\n      exit.onfinish = () => {\n        exits.delete(prev);\n        setPill((layers) => layers.filter((l) => l.key !== prev || !l.rect));\n      };\n    }\n    // Coming back before it had gone: settle back from where it got to.\n    const returning = exits.get(shown);\n    const returningEl = pillRefs.current.get(shown);\n    if (returning && returningEl) {\n      returningEl.animate(fromCurrent(returningEl, PRICE_REST), { duration: 400, easing: EASE_OUT });\n      returning.cancel();\n      exits.delete(shown);\n    }\n    setPill((layers) => {\n      const gone = layers.find((l) => l.key === prev);\n      const back = layers.find((l) => l.key === shown);\n      return [\n        ...layers.filter((l) => l.key !== prev && l.key !== shown),\n        ...(leaving && gone ? [{ ...gone, rect }] : []),\n        back ? { ...back, rect: null } : { key: shown, enter: true, rect: null },\n      ];\n    });\n  }, [shown, reduce]);\n\n  useEffect(() => {\n    const exits = pillExits.current;\n    return () => exits.forEach((exit) => exit.cancel());\n  }, []);\n\n  // The entrance of the ring, the price and the headline. They start hidden\n  // (unless `reveal` is \"none\" or motion is reduced) and transition in once\n  // the section is in view, so the first frame has to be drawn hidden first.\n  const [armed, setArmed] = useState(false);\n  // The stage's ref: once it is in the document, force a layout so the\n  // hidden first frame is what the transitions start from, then arm.\n  const attachStage = useCallback((node: HTMLDivElement | null) => {\n    stageRef.current = node;\n    if (!node) return;\n    node.getBoundingClientRect();\n    setArmed(true);\n  }, []);\n  const [startHidden] = useState(() => !(reveal === \"none\" || reduce));\n  const revealed = reveal === \"none\" || (inView && (armed || !startHidden));\n\n  // Autoplay: one turn after each rest, held while the pointer or focus is on\n  // the ring, while the tab is hidden, or while the section is off screen.\n  useEffect(() => {\n    if (intro || walking || interval <= 0 || held || hidden || !visible || n < 2) return;\n    const t = window.setTimeout(() => choose(active + 1), interval);\n    return () => window.clearTimeout(t);\n  }, [active, intro, walking, interval, held, hidden, visible, n, choose]);\n\n  useEffect(() => {\n    const onVis = () => setHidden(document.hidden);\n    document.addEventListener(\"visibilitychange\", onVis);\n    return () => document.removeEventListener(\"visibilitychange\", onVis);\n  }, []);\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    if (intro) return;\n    if (e.key === \"ArrowRight\") {\n      e.preventDefault();\n      choose(active + 1);\n    } else if (e.key === \"ArrowLeft\") {\n      e.preventDefault();\n      choose(active - 1);\n    }\n  };\n\n  const tiles = useMemo(\n    () =>\n      flavours.map((f, i) => {\n        const rel = ringDistance(i, active, n);\n        // Hidden tiles keep to their own side, whatever the ring says.\n        const side = ring.side[i] ?? Math.sign(rel) ?? 1;\n        const slot = slotFor(Math.abs(rel) >= 3 ? 3 * side : rel, compact);\n        const from = slotFor(3 * side, compact);\n        return { f, i, rel, slot, from, gen: ring.gen[i] ?? 0 };\n      }),\n    [flavours, active, n, compact, ring],\n  );\n\n  const transition = reduce ? null : walking ? QUICK_SPRING : SPRING;\n\n  return (\n    <section\n      className={cn(\"relative w-full overflow-hidden text-[#f4f1e7]\", className)}\n      style={{ background, \"--fc-paper\": paper, ...style } as React.CSSProperties}\n      {...props}\n    >\n      <style>{keyframes}</style>\n      {backgroundImage ? (\n        <>\n          <img\n            src={backgroundImage}\n            alt=\"\"\n            aria-hidden\n            draggable={false}\n            className=\"pointer-events-none absolute inset-0 h-full w-full select-none object-cover\"\n            style={{ objectPosition: backgroundPosition }}\n          />\n        </>\n      ) : (\n        <>\n          <div\n            aria-hidden\n            className=\"pointer-events-none absolute inset-0\"\n            style={{\n              background:\n                \"linear-gradient(180deg, rgba(255,255,255,0.06) 0%, rgba(255,255,255,0) 40%, rgba(0,0,0,0.28) 100%)\",\n            }}\n          />\n          <Mound light={mound[0]} dark={mound[1]} id={id} />\n        </>\n      )}\n\n      <div\n        ref={attachStage}\n        role=\"group\"\n        aria-roledescription=\"carousel\"\n        aria-label=\"Flavours\"\n        tabIndex={0}\n        onKeyDown={onKeyDown}\n        onPointerEnter={() => setHeld(true)}\n        onPointerLeave={() => setHeld(false)}\n        onFocus={() => setHeld(true)}\n        onBlur={(e) => {\n          if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setHeld(false);\n        }}\n        className=\"relative mx-auto aspect-[4/5] w-full max-w-7xl outline-none sm:aspect-[16/11] lg:aspect-[733/426] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-current/50\"\n      >\n        {/* The glow: the flavour's colour, soft, behind the cup. */}\n        <div\n          aria-hidden\n          className=\"pointer-events-none absolute inset-x-[20%] top-[6%] aspect-square rounded-full opacity-40 sm:inset-x-[28%] sm:top-[2%]\"\n          style={{\n            filter: \"blur(70px)\",\n            backgroundColor: current?.tint ?? mound[0],\n            transition: reduce ? \"none\" : `background-color 1.2s ${EASE_OUT_DEFAULT}`,\n          }}\n        />\n\n        {/* ---- The ring of tiles: one band across the middle ---- */}\n        <div\n          className={cn(\"absolute inset-0 z-10\", intro && \"pointer-events-none\")}\n          style={{\n            translate: revealed ? \"0 0\" : \"0 70%\",\n            opacity: revealed ? 1 : 0,\n            transition: reduce\n              ? \"none\"\n              : `translate 1.9s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.5s ${EASE_OUT_DEFAULT}`,\n          }}\n        >\n          {tiles.map(({ f, i, rel, slot, from, gen: g }) => (\n            <Tile\n              key={`${f.name}${i}:${g}`}\n              flavour={f}\n              index={i}\n              n={n}\n              rel={rel}\n              slot={slot}\n              from={g > 0 ? from : null}\n              size={tile}\n              width={width}\n              height={height}\n              compact={compact}\n              phase={phase}\n              spinning={intro}\n              transition={transition}\n              reduce={!!reduce}\n              onChoose={choose}\n            />\n          ))}\n        </div>\n\n        {/* ---- The cup, standing on the peak: every picture stacked, the newest on top ---- */}\n        <div\n          ref={cupRef}\n          className=\"pointer-events-none absolute bottom-[33%] left-1/2 z-20 w-[46%] -translate-x-1/2 drop-shadow-[0_40px_40px_rgba(0,0,0,0.5)] sm:w-[30%] lg:w-[24.6%]\"\n          style={{ aspectRatio: \"357 / 462\" }}\n        >\n          {flavours.map((f, i) => {\n            const rank = order.indexOf(i);\n            return (\n              <img\n                key={f.product + i}\n                data-fc-product={i}\n                src={f.product}\n                alt={i === shown ? (f.alt ?? f.name) : \"\"}\n                draggable={false}\n                className=\"absolute inset-0 h-full w-full select-none object-contain\"\n                style={{ zIndex: rank < 0 ? 0 : rank + 1, opacity: rank < 0 ? 0 : 1 }}\n              />\n            );\n          })}\n        </div>\n\n        {/* ---- The powder, in front of the cup, so the glass stands in it ---- */}\n        {foregroundImage && (\n          <>\n            <img\n              src={foregroundImage}\n              alt=\"\"\n              aria-hidden\n              draggable={false}\n              className=\"pointer-events-none absolute bottom-0 left-1/2 z-[25] w-auto max-w-none -translate-x-1/2 select-none\"\n              style={{ height: `${foregroundHeight * 100}%` }}\n            />\n          </>\n        )}\n\n        {/* ---- Under the cup: the price, then the cart ---- */}\n        <div\n          className=\"absolute inset-x-0 top-[61.5%] z-30 flex flex-col items-center\"\n          style={{\n            gap: pillHeight * 0.25,\n            translate: revealed ? \"0 0\" : \"0 16px\",\n            opacity: revealed ? 1 : 0,\n            transition: reduce ? \"none\" : `translate 0.7s ${EASE_OUT} 1.5s, opacity 0.7s ${EASE_OUT} 1.5s`,\n          }}\n        >\n          <div\n            className=\"relative min-w-[3.5em] overflow-hidden rounded-full text-[#1b2012] shadow-[0_12px_24px_-12px_rgba(0,0,0,0.6)]\"\n            style={{ background: paper, height: pillHeight, paddingInline: pillHeight * 0.45, fontSize: pillFont }}\n            aria-live=\"polite\"\n          >\n            {pill.map((layer) => {\n              const f = flavours[layer.key];\n              return (\n                <div\n                  key={layer.key}\n                  ref={(el) => {\n                    if (el) pillRefs.current.set(layer.key, el);\n                    else pillRefs.current.delete(layer.key);\n                  }}\n                  className=\"flex h-full items-center justify-center whitespace-nowrap font-semibold tracking-[0.01em]\"\n                  style={{\n                    animation: layer.enter ? `flavour-carousel-price-in 0.4s ${EASE_OUT} backwards` : undefined,\n                    ...(layer.rect && { position: \"absolute\", ...layer.rect }),\n                  }}\n                >\n                  <span className=\"sr-only\">{f?.name}: </span>\n                  {f?.price ?? f?.name}\n                </div>\n              );\n            })}\n          </div>\n          {onAdd && (\n            <Button\n              variant=\"default\"\n              size=\"sm\"\n              aria-label={`${addLabel}: ${current?.name}`}\n              onClick={() => onAdd(current, shown)}\n              iconLeft={<ShoppingCart size={cartSize * 0.4} />}\n              style={{ width: cartSize, height: cartSize }}\n              className=\"rounded-full border-0 bg-[var(--fc-paper)] text-[#1b2012] shadow-[0_12px_24px_-12px_rgba(0,0,0,0.6)] hover:bg-white\"\n            />\n          )}\n        </div>\n\n        {/* ---- The headline, low over the powder ---- */}\n        {heading && (\n          <h2\n            className=\"absolute inset-x-4 top-[92%] z-30 text-center sm:top-[89%] font-serif font-normal leading-[1.05] tracking-[-0.02em] [text-shadow:0_2px_24px_rgba(0,0,0,0.45)]\"\n            style={{\n              fontSize: headingSize,\n              transform: \"translateY(-50%)\",\n              opacity: revealed ? 1 : 0,\n              transition: reduce ? \"none\" : `opacity 0.8s ${EASE_OUT} 1.7s`,\n            }}\n          >\n            {heading}\n          </h2>\n        )}\n      </div>\n    </section>\n  );\n}\n\nexport default FlavourCarousel;\n",
      "type": "registry:component",
      "target": "components/custom/blocks/FlavourCarouselBlock.tsx"
    },
    {
      "path": "src/components/custom/blocks/motion-curves.ts",
      "content": "/**\n * Motion curves with no animation library behind them.\n *\n * The components here ship as CSS, GSAP or Motion builds that must move\n * identically, so the curves are computed once, from the same numbers, and\n * handed to whichever engine runs them:\n *\n *   - `cubicBezier(x1, y1, x2, y2)` → an easing function (GSAP accepts any\n *     `(progress) => value` as `ease`), exact for Motion's `ease: [..]` arrays\n *     and for CSS `cubic-bezier()`.\n *   - `spring({ stiffness, damping, mass })` → the analytic solution Motion\n *     Motion uses, as an easing function plus the time it takes to settle, or\n *     as a CSS `linear()` string for a fixed start and end.\n *   - `createSpringFollower` → a value that chases a moving target through the\n *     same spring every frame, like Motion's `useSpring`, for pointer-driven\n *     motion that no fixed curve can describe.\n */\n\n// ---------------------------------------------------------------------------\n// Cubic bezier\n// ---------------------------------------------------------------------------\n\n/**\n * The CSS / Motion cubic-bezier as a function of progress. Newton-Raphson\n * with a bisection fallback, the same solver browsers use.\n */\nexport function cubicBezier(x1: number, y1: number, x2: number, y2: number) {\n  if (x1 === y1 && x2 === y2) return (t: number) => t;\n\n  const a = (p1: number, p2: number) => 1 - 3 * p2 + 3 * p1;\n  const b = (p1: number, p2: number) => 3 * p2 - 6 * p1;\n  const c = (p1: number) => 3 * p1;\n  const at = (t: number, p1: number, p2: number) =>\n    ((a(p1, p2) * t + b(p1, p2)) * t + c(p1)) * t;\n  const slope = (t: number, p1: number, p2: number) =>\n    3 * a(p1, p2) * t * t + 2 * b(p1, p2) * t + c(p1);\n\n  const solveX = (x: number) => {\n    let t = x;\n    for (let i = 0; i < 8; i++) {\n      const s = slope(t, x1, x2);\n      if (Math.abs(s) < 1e-6) break;\n      const err = at(t, x1, x2) - x;\n      if (Math.abs(err) < 1e-7) return t;\n      t -= err / s;\n    }\n    let lo = 0;\n    let hi = 1;\n    t = x;\n    for (let i = 0; i < 30 && hi - lo > 1e-7; i++) {\n      const value = at(t, x1, x2);\n      if (value < x) lo = t;\n      else hi = t;\n      t = (lo + hi) / 2;\n    }\n    return t;\n  };\n\n  return (x: number) => (x <= 0 ? 0 : x >= 1 ? 1 : at(solveX(x), y1, y2));\n}\n\n/** Motion's named eases, as the cubic-beziers they are. */\nexport const MOTION_EASE = {\n  linear: [0, 0, 1, 1],\n  easeIn: [0.42, 0, 1, 1],\n  easeOut: [0, 0, 0.58, 1],\n  easeInOut: [0.42, 0, 0.58, 1],\n  circIn: [0.55, 0, 1, 0.45],\n  circOut: [0.55, 0, 0.45, 1],\n  circInOut: [0.85, 0, 0.15, 1],\n  backIn: [0.31, 0.01, 0.66, -0.59],\n  backOut: [0.33, 1.53, 0.69, 0.99],\n  anticipate: [0.66, -0.56, 0.34, 1.35],\n} as const;\n\n/**\n * Motion's default layout transition (`layout` / `layoutId`):\n * `{ duration: 0.45, ease: [0.4, 0, 0.1, 1] }`.\n */\nexport const LAYOUT_TRANSITION = { duration: 0.45, ease: [0.4, 0, 0.1, 1] as const };\n\n// ---------------------------------------------------------------------------\n// Spring\n// ---------------------------------------------------------------------------\n\nexport interface SpringOptions {\n  /** Motion default 100. */\n  stiffness?: number;\n  /** Motion default 10. */\n  damping?: number;\n  /** Motion default 1. */\n  mass?: number;\n  /** Starting velocity, in units of the whole distance per second. */\n  velocity?: number;\n  /** How close to the end counts as settled, as a fraction of the distance. */\n  restDelta?: number;\n}\n\n/**\n * Normalised position (0 → 1) of a spring released from 0 towards 1, at time\n * `t` seconds. The closed-form solution Motion's `spring()` generator\n * uses for the under-, critically and over-damped cases.\n */\nexport function springAt(options: SpringOptions = {}) {\n  const { stiffness = 100, damping = 10, mass = 1, velocity = 0 } = options;\n  const zeta = damping / (2 * Math.sqrt(stiffness * mass));\n  const omega0 = Math.sqrt(stiffness / mass);\n  // Motion's convention: distance still to cover, velocity toward it negated.\n  const delta = 1;\n  const v0 = -velocity;\n\n  if (zeta < 1) {\n    const omegaD = omega0 * Math.sqrt(1 - zeta * zeta);\n    return (t: number) => {\n      const envelope = Math.exp(-zeta * omega0 * t);\n      return (\n        1 -\n        envelope *\n          (((v0 + zeta * omega0 * delta) / omegaD) * Math.sin(omegaD * t) +\n            delta * Math.cos(omegaD * t))\n      );\n    };\n  }\n  if (zeta === 1) {\n    return (t: number) => 1 - Math.exp(-omega0 * t) * (delta + (v0 + omega0 * delta) * t);\n  }\n  const omegaD = omega0 * Math.sqrt(zeta * zeta - 1);\n  return (t: number) => {\n    const envelope = Math.exp(-zeta * omega0 * t);\n    const freq = Math.min(omegaD * t, 300);\n    return (\n      1 -\n      (envelope *\n        ((v0 + zeta * omega0 * delta) * Math.sinh(freq) + omegaD * delta * Math.cosh(freq))) /\n        omegaD\n    );\n  };\n}\n\n/** Seconds until the spring stays within `restDelta` of its end. */\nexport function springDuration(options: SpringOptions = {}) {\n  const at = springAt(options);\n  const restDelta = options.restDelta ?? 0.001;\n  const step = 1 / 240;\n  let lastOutside = 0;\n  for (let t = 0; t <= 10; t += step) {\n    if (Math.abs(1 - at(t)) > restDelta) lastOutside = t;\n    else if (t - lastOutside > 0.1) break;\n  }\n  return Math.max(lastOutside + step, step);\n}\n\n/**\n * A spring as a duration and an easing function over it — what GSAP takes:\n *\n *   const { duration, ease } = springEase({ stiffness: 300, damping: 20 });\n *   gsap.to(el, { y: 0, duration, ease });\n *\n * Exact for a fixed start and end; a spring that has to react mid-flight to a\n * new target needs `createSpringFollower` instead.\n */\nexport function springEase(options: SpringOptions = {}) {\n  const duration = springDuration(options);\n  const at = springAt(options);\n  return {\n    duration,\n    ease: (progress: number) => (progress >= 1 ? 1 : at(progress * duration)),\n  };\n}\n\n/**\n * A spring as a CSS `linear()` easing and its duration in ms, for\n * `transition` / `animation` with a fixed start and end.\n *\n *   const { easing, duration } = springLinear({ stiffness: 400, damping: 30 });\n *   el.style.transition = `transform ${duration}ms ${easing}`;\n */\nexport function springLinear(options: SpringOptions = {}, pointsPerSecond = 60) {\n  const duration = springDuration(options);\n  const at = springAt(options);\n  const count = Math.max(Math.ceil(duration * pointsPerSecond), 8);\n  const points: string[] = [];\n  for (let i = 0; i <= count; i++) {\n    const t = (i / count) * duration;\n    points.push(String(Math.round((i === count ? 1 : at(t)) * 10000) / 10000));\n  }\n  return { easing: `linear(${points.join(\", \")})`, duration: Math.round(duration * 1000) };\n}\n\n// ---------------------------------------------------------------------------\n// Spring follower (useSpring equivalent)\n// ---------------------------------------------------------------------------\n\n/** Something that calls back once per frame with the time since the last, in ms. */\nexport interface FrameTicker {\n  add: (callback: (deltaMs: number) => void) => () => void;\n}\n\n/** requestAnimationFrame as a ticker — the library-free default. */\nexport const rafTicker: FrameTicker = {\n  add(callback) {\n    let last = performance.now();\n    let frame = requestAnimationFrame(function tick(now) {\n      callback(now - last);\n      last = now;\n      frame = requestAnimationFrame(tick);\n    });\n    return () => cancelAnimationFrame(frame);\n  },\n};\n\nexport interface SpringFollower {\n  /** Chase a new target from wherever the value is now, keeping its velocity. */\n  set: (target: number) => void;\n  /** Move to a value instantly, with no motion. */\n  jump: (value: number) => void;\n  get: () => number;\n  destroy: () => void;\n}\n\n/**\n * A value that follows its target through a spring, integrating the same\n * equation of motion Motion's `useSpring` solves — so a pointer-driven spring\n * reads the same in every build. Runs only while moving; `onUpdate` receives\n * each new value.\n */\nexport function createSpringFollower(\n  initial: number,\n  onUpdate: (value: number) => void,\n  options: SpringOptions & { restSpeed?: number; ticker?: FrameTicker } = {},\n): SpringFollower {\n  const { stiffness = 100, damping = 10, mass = 1, ticker = rafTicker } = options;\n  const restDelta = options.restDelta ?? 0.01;\n  const restSpeed = options.restSpeed ?? 0.01;\n  let value = initial;\n  let target = initial;\n  let velocity = 0;\n  let stop: (() => void) | null = null;\n\n  const step = (deltaMs: number) => {\n    // Fixed 1ms sub-steps keep the integration stable for stiff springs and\n    // independent of the frame rate.\n    const steps = Math.min(Math.max(Math.round(deltaMs), 1), 250);\n    for (let i = 0; i < steps; i++) {\n      const force = -stiffness * (value - target) - damping * velocity;\n      velocity += (force / mass) * 0.001;\n      value += velocity * 0.001;\n    }\n    if (Math.abs(target - value) < restDelta && Math.abs(velocity) < restSpeed) {\n      value = target;\n      velocity = 0;\n      stop?.();\n      stop = null;\n    }\n    onUpdate(value);\n  };\n\n  return {\n    set(next) {\n      target = next;\n      if (!stop && value !== target) stop = ticker.add(step);\n    },\n    jump(next) {\n      stop?.();\n      stop = null;\n      value = target = next;\n      velocity = 0;\n      onUpdate(value);\n    },\n    get: () => value,\n    destroy() {\n      stop?.();\n      stop = null;\n    },\n  };\n}\n",
      "type": "registry:component",
      "target": "components/custom/blocks/motion-curves.ts"
    }
  ],
  "docs": "Named export: FlavourCarousel. Composed from the button item, which installs alongside it. Pass `flavours` ({ name, price?, tint?, product, tile }[] — every product image must share the same crop), `heading`, `interval` in ms (0 turns autoplay off), `initial`, `reveal` (in-view, immediate or none), `onChange` and `onAdd` (omit it to hide the cart button) with `addLabel`. `backgroundImage` is the backdrop and `foregroundImage` the transparent powder cutout laid in front of the cup (`foregroundHeight` of the stage tall); without them the scene is drawn from `background`, `mound` ([light, dark]) and `paper`.",
  "categories": [
    "marketing",
    "commerce",
    "media"
  ],
  "type": "registry:component"
}
