{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"card-carousel-3d","type":"registry:component","title":"3D Card Carousel","description":"A coverflow carousel: cards on an arc, the front one facing you while its neighbours turn in, dim and blur with depth. Drag or swipe with momentum that snaps to a card, arrows, dots, keyboard, tap a side card. No dependencies.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/card-carousel-3d.tsx","content":"\"use client\";\n\n/*\n * CardCarousel3D: a coverflow carousel. Cards sit on an arc in front of you: the\n * current card faces forward, its neighbours turn toward it, tuck back in depth,\n * dim and blur a little more the further they are.\n *\n * One continuous number (pos) says which card is in front. Every card's pose is a\n * pure function of its signed distance to pos, written straight to the DOM from a\n * single requestAnimationFrame loop that sleeps when everything is at rest. Drag\n * or swipe moves pos 1:1, release throws it (velocity projected, then snapped to a\n * card) and a hand-written spring settles it. Arrows, dots, keyboard, a trackpad\n * swipe and a tap on a side card all move the same spring target.\n * No animation library; sizes come from one CSS variable (--cc3d-card-w).\n * Reduced motion drops the spring and the pointer parallax: cards jump into place.\n */\n\nimport { useEffect, useId, useRef, useState, type CSSProperties, type KeyboardEvent, type PointerEvent, type ReactNode } from \"react\";\n\nexport interface CardCarousel3DProps {\n  /** Card titles, one per card. */\n  cards?: string[];\n  /** Replaces the built-in card face. Receives the title, its index and whether it is the current card. */\n  renderCard?: (card: string, index: number, active: boolean) => ReactNode;\n  /** Which card starts in front. */\n  defaultIndex?: number;\n  /** Called with the new index whenever the card in front changes. */\n  onChange?: (index: number) => void;\n  /** Wrap around at the ends (needs 3+ cards). When false the ends resist and the arrows disable. */\n  loop?: boolean;\n  /** Accessible name of the carousel. */\n  label?: string;\n  /** Extra classes for the root. Set the card width with a class like [--cc3d-card-w:240px]. */\n  className?: string;\n}\n\nconst DEFAULT_CARDS = [\"Design\", \"Build\", \"Ship\", \"Iterate\"];\n\n/* ---- Motion and geometry constants -------------------------------------- */\n\n/** Spring toward the target card: stiffness, damping (ratio ~0.94, no visible overshoot). */\nconst SPRING_K = 150;\nconst SPRING_C = 23;\n/** Distance from the front card to its first neighbour, in card widths. Drag maps 1 card to this much pointer travel. */\nconst STEP = 0.74;\n/** Extra spacing per card beyond the first neighbour. */\nconst FAR_STEP = 0.36;\n/** Angle the neighbours turn toward the front card, in degrees. */\nconst TURN = 46;\n/** How far a release throw is projected: seconds of velocity added to the position. */\nconst THROW = 0.17;\n/** Pointer travel (px) before a press becomes a drag. */\nconst DRAG_SLOP = 5;\n\nconst clamp = (v: number, a: number, b: number) => Math.min(b, Math.max(a, v));\nconst f4 = (v: number) => (Math.abs(v) < 0.00005 ? \"0\" : v.toFixed(4));\nconst mod = (a: number, n: number) => ((a % n) + n) % n;\n\n/* ---- Pose: everything about a card is a function of its signed distance d to the front card ---- */\n\ninterface Pose {\n  transform: string;\n  opacity: string;\n  zIndex: string;\n  visibility: \"visible\" | \"hidden\";\n  filter: string;\n  dim: string;\n  sheen: string;\n  focus: string;\n}\n\nfunction pose(d: number, n: number, loop: boolean): Pose {\n  const a = Math.abs(d);\n  const s = d < 0 ? -1 : 1;\n  const near = Math.min(a, 1);\n  const far = Math.min(Math.max(a - 1, 0), 2.5);\n  const x = s * (near * STEP + far * FAR_STEP);\n  const z = -(near * 0.42 + far * 0.2);\n  const rot = -s * near * TURN;\n  const scale = 1 - near * 0.04 - far * 0.05;\n  let op = a < 1.4 ? 1 : a < 2.2 ? 1 - (a - 1.4) * 0.55 : a < 3.2 ? 0.56 * (3.2 - a) : 0;\n  if (loop) op *= clamp((n / 2 - a) / 0.7, 0, 1);\n  const blur = Math.min(a, 2.2) * 1.15;\n  return {\n    transform: `translate3d(calc(var(--cc-w) * ${f4(x)}), 0, calc(var(--cc-w) * ${f4(z)})) rotateY(${f4(rot)}deg) scale(${f4(scale)})`,\n    opacity: f4(op),\n    zIndex: String(1000 - Math.round(a * 100)),\n    visibility: op > 0.01 ? \"visible\" : \"hidden\",\n    filter: blur < 0.05 ? \"none\" : `blur(${blur.toFixed(2)}px)`,\n    dim: f4(near * 0.3 + far * 0.1),\n    sheen: `${(50 - d * 40).toFixed(1)}%`,\n    focus: f4(1 - near),\n  };\n}\n\n/* ---- Engine: mutable animation state, touched only from effects and handlers ---- */\n\ninterface Drag {\n  id: number;\n  x0: number;\n  k: number;\n  w: number;\n  base: number;\n  moved: boolean;\n  lastPos: number;\n  lastT: number;\n  v: number;\n}\n\ninterface Engine {\n  pos: number;\n  vel: number;\n  target: number;\n  dragging: boolean;\n  drag: Drag | null;\n  glare: number;\n  glareT: number;\n  px: number;\n  py: number;\n  pxT: number;\n  pyT: number;\n  reduced: boolean;\n  n: number;\n  loop: boolean;\n  active: number;\n  justDragged: boolean;\n  onChange: ((i: number) => void) | undefined;\n  wake: () => void;\n  setActive: (i: number) => void;\n}\n\nfunction makeEngine(index: number, n: number, loop: boolean): Engine {\n  return {\n    pos: index, vel: 0, target: index, dragging: false, drag: null,\n    glare: 0, glareT: 0, px: 0, py: 0, pxT: 0, pyT: 0,\n    reduced: false, n, loop, active: index, justDragged: false,\n    onChange: undefined, wake: () => {}, setActive: () => {},\n  };\n}\n\nfunction paint(E: Engine, cards: (HTMLDivElement | null)[], faces: (HTMLDivElement | null)[], stage: HTMLDivElement | null) {\n  for (let i = 0; i < E.n; i++) {\n    const el = cards[i];\n    if (!el) continue;\n    let d = i - E.pos;\n    if (E.loop) d -= E.n * Math.round(d / E.n);\n    const p = pose(d, E.n, E.loop);\n    const st = el.style;\n    st.transform = p.transform;\n    st.opacity = p.opacity;\n    st.zIndex = p.zIndex;\n    st.visibility = p.visibility;\n    st.setProperty(\"--dim\", p.dim);\n    st.setProperty(\"--sheen\", p.sheen);\n    st.setProperty(\"--focus\", p.focus);\n    const face = faces[i];\n    if (face) face.style.filter = p.filter;\n  }\n  if (stage) {\n    stage.style.perspectiveOrigin = `${(50 + E.px * 7).toFixed(2)}% ${(42 + E.py * 5).toFixed(2)}%`;\n    stage.style.setProperty(\"--glare\", E.glare.toFixed(3));\n  }\n}\n\n/** Past the ends (loop off) the position resists like a rubber band. */\nfunction rubber(p: number, max: number) {\n  const r = (x: number) => 0.55 * (1 - Math.exp(-x * 1.4));\n  return p < 0 ? -r(-p) : p > max ? max + r(p - max) : p;\n}\n\n/* ---- Default card art ---------------------------------------------------- */\n\nconst PALETTES: [string, string][] = [\n  [\"#ff7a59\", \"#ffc46b\"],\n  [\"#4cc9f0\", \"#5b6cff\"],\n  [\"#c08bff\", \"#ff5fa2\"],\n  [\"#b8f35c\", \"#19b9a6\"],\n  [\"#ffd166\", \"#ef476f\"],\n  [\"#7ef0d2\", \"#4a8cff\"],\n];\nconst FALLBACK_PALETTE: [string, string] = [\"#ff7a59\", \"#ffc46b\"];\n\nfunction Art({ variant, a, b, uid }: { variant: number; a: string; b: string; uid: string }) {\n  const g = `${uid}g`;\n  const o = `${uid}o`;\n  const m = `${uid}m`;\n  return (\n    <svg aria-hidden className=\"absolute inset-0 h-full w-full\" viewBox=\"0 0 100 130\" preserveAspectRatio=\"xMidYMid slice\">\n      <defs>\n        <linearGradient id={g} x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\">\n          <stop offset=\"0\" stopColor={a} />\n          <stop offset=\"1\" stopColor={b} />\n        </linearGradient>\n        <radialGradient id={o} cx=\"50%\" cy=\"42%\" r=\"58%\">\n          <stop offset=\"0\" stopColor={a} stopOpacity=\"0.95\" />\n          <stop offset=\"0.55\" stopColor={b} stopOpacity=\"0.55\" />\n          <stop offset=\"1\" stopColor={b} stopOpacity=\"0\" />\n        </radialGradient>\n        <mask id={m}>\n          <rect width=\"100\" height=\"130\" fill=\"#fff\" />\n          <circle cx=\"72\" cy=\"36\" r=\"30\" fill=\"#000\" />\n        </mask>\n      </defs>\n      {variant === 0 && (\n        <g>\n          <circle cx=\"58\" cy=\"46\" r=\"36\" fill={`url(#${o})`} />\n          <g fill=\"none\" stroke=\"#fff\" strokeOpacity=\"0.2\" strokeWidth=\"0.35\">\n            <circle cx=\"58\" cy=\"46\" r=\"14\" />\n            <circle cx=\"58\" cy=\"46\" r=\"24\" />\n            <circle cx=\"58\" cy=\"46\" r=\"35\" />\n            <circle cx=\"58\" cy=\"46\" r=\"48\" />\n          </g>\n        </g>\n      )}\n      {variant === 1 && (\n        <g fill=\"none\" strokeLinecap=\"round\">\n          <path d=\"M-8 92 C 20 30, 62 108, 110 38\" stroke={`url(#${g})`} strokeWidth=\"13\" strokeOpacity=\"0.95\" />\n          <path d=\"M-8 80 C 22 18, 64 96, 110 26\" stroke=\"#fff\" strokeWidth=\"0.5\" strokeOpacity=\"0.4\" />\n          <path d=\"M-8 106 C 20 46, 62 124, 110 54\" stroke={`url(#${g})`} strokeWidth=\"5\" strokeOpacity=\"0.5\" />\n        </g>\n      )}\n      {variant === 2 && (\n        <g transform=\"rotate(-14 50 50)\">\n          <rect x=\"6\" y=\"22\" width=\"76\" height=\"11\" rx=\"5.5\" fill={`url(#${g})`} />\n          <rect x=\"22\" y=\"38\" width=\"70\" height=\"11\" rx=\"5.5\" fill={`url(#${g})`} fillOpacity=\"0.75\" />\n          <rect x=\"2\" y=\"54\" width=\"58\" height=\"11\" rx=\"5.5\" fill={`url(#${g})`} fillOpacity=\"0.55\" />\n          <rect x=\"30\" y=\"70\" width=\"64\" height=\"11\" rx=\"5.5\" fill={`url(#${g})`} fillOpacity=\"0.35\" />\n        </g>\n      )}\n      {variant === 3 && (\n        <g>\n          <circle cx=\"56\" cy=\"46\" r=\"36\" fill={`url(#${g})`} mask={`url(#${m})`} />\n          <circle cx=\"56\" cy=\"46\" r=\"42\" fill=\"none\" stroke=\"#fff\" strokeOpacity=\"0.16\" strokeWidth=\"0.35\" />\n        </g>\n      )}\n    </svg>\n  );\n}\n\nfunction DefaultFace({ title, index, total, uid }: { title: string; index: number; total: number; uid: string }) {\n  const [a, b] = PALETTES[index % PALETTES.length] ?? FALLBACK_PALETTE;\n  const num = String(index + 1).padStart(2, \"0\");\n  return (\n    <div className=\"absolute inset-0\">\n      <div\n        aria-hidden\n        className=\"absolute inset-0\"\n        style={{\n          background: `radial-gradient(90% 62% at 72% 14%, ${a}44, transparent 70%), radial-gradient(80% 50% at 6% 100%, ${b}33, transparent 72%)`,\n        }}\n      />\n      <Art variant={index % 4} a={a} b={b} uid={uid} />\n      <div aria-hidden className=\"absolute inset-0\" style={{ background: \"linear-gradient(to top, rgba(8,9,12,0.94) 0%, rgba(8,9,12,0.55) 34%, rgba(8,9,12,0) 62%)\" }} />\n      <div\n        className=\"absolute inset-x-[8%] top-[6%] flex items-center justify-between font-medium text-white/75\"\n        style={{ fontFamily: \"ui-monospace, SFMono-Regular, Menlo, monospace\", fontSize: \"max(10px, calc(var(--cc-w) * 0.044))\", letterSpacing: \"0.16em\" }}\n      >\n        <span>{num}</span>\n        <span\n          className=\"flex items-center justify-center rounded-full text-white/85\"\n          style={{ width: \"calc(var(--cc-w) * 0.11)\", height: \"calc(var(--cc-w) * 0.11)\", background: \"rgba(255,255,255,0.1)\", boxShadow: \"inset 0 0 0 1px rgba(255,255,255,0.22)\" }}\n        >\n          <svg aria-hidden viewBox=\"0 0 16 16\" width=\"52%\" height=\"52%\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n            <path d=\"M4.5 11.5 11.5 4.5M5.5 4.5h6v6\" />\n          </svg>\n        </span>\n      </div>\n      <div className=\"absolute inset-x-[8%] bottom-[7%] text-white\">\n        <div className=\"break-words font-semibold\" style={{ fontSize: \"calc(var(--cc-w) * 0.13)\", lineHeight: 1.04, letterSpacing: \"-0.035em\" }}>\n          {title}\n        </div>\n        <div\n          className=\"mt-[4%] flex items-center gap-[3%] text-white/55\"\n          style={{ fontFamily: \"ui-monospace, SFMono-Regular, Menlo, monospace\", fontSize: \"max(9px, calc(var(--cc-w) * 0.038))\", letterSpacing: \"0.18em\" }}\n        >\n          <span className=\"h-px flex-1\" style={{ background: \"rgba(255,255,255,0.22)\" }} />\n          <span>\n            {num} / {String(total).padStart(2, \"0\")}\n          </span>\n        </div>\n      </div>\n    </div>\n  );\n}\n\n/* ---- Component ----------------------------------------------------------- */\n\nconst RING =\n  \"focus-visible:!outline-2 focus-visible:!outline-offset-2 focus-visible:!outline-[#5b9bff]\";\nconst BTN =\n  \"flex h-10 w-10 shrink-0 cursor-pointer items-center justify-center rounded-full bg-transparent transition-[background-color,transform,opacity] duration-200 hover:bg-[color-mix(in_srgb,currentColor_12%,transparent)] active:scale-90 disabled:cursor-default disabled:opacity-30 disabled:hover:bg-transparent disabled:active:scale-100 focus-visible:!rounded-full\";\n\nexport function CardCarousel3D({\n  cards = DEFAULT_CARDS,\n  renderCard,\n  defaultIndex = 0,\n  onChange,\n  loop = true,\n  label = \"Card carousel\",\n  className = \"\",\n}: CardCarousel3DProps) {\n  const n = cards.length;\n  const looping = loop && n >= 3;\n  const uid = useId().replace(/[^a-zA-Z0-9]/g, \"\");\n  const [initial] = useState(() => clamp(Math.round(defaultIndex), 0, Math.max(0, n - 1)));\n  const [active, setActive] = useState(initial);\n  const eng = useRef<Engine>(makeEngine(initial, n, looping));\n  const stageRef = useRef<HTMLDivElement>(null);\n  const rootRef = useRef<HTMLDivElement>(null);\n  const cardEls = useRef<(HTMLDivElement | null)[]>([]);\n  const faceEls = useRef<(HTMLDivElement | null)[]>([]);\n\n  /* The one animation loop: spring, pointer smoothing, paint. Sleeps at rest. */\n  useEffect(() => {\n    const E = eng.current;\n    let raf = 0;\n    let last = 0;\n    const frame = (t: number) => {\n      raf = 0;\n      const dt = last ? Math.min(0.05, (t - last) / 1000) : 1 / 60;\n      last = t;\n      if (!E.dragging) {\n        if (E.reduced) {\n          E.pos = E.target;\n          E.vel = 0;\n        } else {\n          let rem = dt;\n          while (rem > 1e-6) {\n            const h = Math.min(rem, 1 / 120);\n            E.vel += (SPRING_K * (E.target - E.pos) - SPRING_C * E.vel) * h;\n            E.pos += E.vel * h;\n            rem -= h;\n          }\n        }\n      }\n      const gk = 1 - Math.exp(-dt * 9);\n      E.glare += (E.glareT - E.glare) * gk;\n      E.px += (E.pxT - E.px) * gk;\n      E.py += (E.pyT - E.py) * gk;\n      const settled =\n        !E.dragging && Math.abs(E.target - E.pos) < 0.0004 && Math.abs(E.vel) < 0.004 &&\n        Math.abs(E.glareT - E.glare) < 0.004 && Math.abs(E.pxT - E.px) < 0.003 && Math.abs(E.pyT - E.py) < 0.003;\n      if (settled) {\n        E.pos = E.target;\n        E.vel = 0;\n        E.glare = E.glareT;\n        E.px = E.pxT;\n        E.py = E.pyT;\n      }\n      paint(E, cardEls.current, faceEls.current, stageRef.current);\n      const idx = E.loop ? mod(Math.round(E.pos), E.n) : clamp(Math.round(E.pos), 0, Math.max(0, E.n - 1));\n      if (idx !== E.active) {\n        E.active = idx;\n        E.setActive(idx);\n        E.onChange?.(idx);\n      }\n      if (settled) last = 0;\n      else raf = requestAnimationFrame(frame);\n    };\n    E.wake = () => {\n      if (!raf) raf = requestAnimationFrame(frame);\n    };\n    E.setActive = setActive;\n    paint(E, cardEls.current, faceEls.current, stageRef.current);\n    return () => {\n      cancelAnimationFrame(raf);\n      raf = 0;\n      E.wake = () => {};\n    };\n  }, []);\n\n  /* Props that the loop reads. */\n  useEffect(() => {\n    const E = eng.current;\n    E.n = n;\n    E.loop = looping;\n    E.onChange = onChange;\n    if (!looping) {\n      E.target = clamp(Math.round(E.target), 0, Math.max(0, n - 1));\n      E.pos = clamp(E.pos, 0, Math.max(0, n - 1));\n    }\n    paint(E, cardEls.current, faceEls.current, stageRef.current);\n    E.wake();\n  }, [n, looping, onChange]);\n\n  /* Reduced motion: no spring, no parallax; cards jump into place. */\n  useEffect(() => {\n    const E = eng.current;\n    const mq = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n    const sync = () => {\n      E.reduced = mq.matches;\n      if (mq.matches) {\n        E.glareT = 0;\n        E.pxT = 0;\n        E.pyT = 0;\n      }\n      E.wake();\n    };\n    sync();\n    mq.addEventListener(\"change\", sync);\n    return () => mq.removeEventListener(\"change\", sync);\n  }, []);\n\n  /* A horizontal trackpad swipe steps one card per gesture. */\n  useEffect(() => {\n    const stage = stageRef.current;\n    if (!stage) return;\n    const E = eng.current;\n    let acc = 0;\n    let armed = true;\n    let lastT = 0;\n    const onWheel = (e: WheelEvent) => {\n      if (Math.abs(e.deltaX) <= Math.abs(e.deltaY) * 1.2) return;\n      e.preventDefault();\n      if (e.timeStamp - lastT > 140) {\n        armed = true;\n        acc = 0;\n      }\n      lastT = e.timeStamp;\n      if (!armed) return;\n      acc += e.deltaX;\n      if (Math.abs(acc) > 36) {\n        step(E, acc > 0 ? 1 : -1);\n        armed = false;\n        acc = 0;\n      }\n    };\n    stage.addEventListener(\"wheel\", onWheel, { passive: false });\n    return () => stage.removeEventListener(\"wheel\", onWheel);\n  }, []);\n\n  /* Keyboard focus follows the front card, so arrow keys keep working from where you were. */\n  useEffect(() => {\n    const at = document.activeElement;\n    if (!at || !rootRef.current?.contains(at)) return;\n    const els = cardEls.current;\n    if (els.includes(at as HTMLDivElement)) els[active]?.focus({ preventScroll: true });\n  }, [active]);\n\n  /* ---- handlers (only ever run from events) ---- */\n\n  const onPointerDown = (e: PointerEvent<HTMLDivElement>) => {\n    const E = eng.current;\n    const stage = stageRef.current;\n    if (!stage || n < 2 || (e.pointerType === \"mouse\" && e.button !== 0)) return;\n    const rect = stage.getBoundingClientRect();\n    E.drag = {\n      id: e.pointerId,\n      x0: e.clientX,\n      k: rect.width ? stage.offsetWidth / rect.width : 1,\n      w: cardEls.current[E.active]?.offsetWidth || 200,\n      base: E.pos,\n      moved: false,\n      lastPos: E.pos,\n      lastT: e.timeStamp,\n      v: 0,\n    };\n  };\n\n  const onPointerMove = (e: PointerEvent<HTMLDivElement>) => {\n    const E = eng.current;\n    const stage = stageRef.current;\n    const dr = E.drag;\n    if (dr && dr.id === e.pointerId) {\n      const dx = (e.clientX - dr.x0) * dr.k;\n      if (!dr.moved && Math.abs(dx) > DRAG_SLOP) {\n        dr.moved = true;\n        E.dragging = true;\n        E.glareT = 0;\n        stage?.setPointerCapture(e.pointerId);\n      }\n      if (dr.moved) {\n        const raw = dr.base - dx / (dr.w * STEP);\n        const p = E.loop ? raw : rubber(raw, Math.max(0, E.n - 1));\n        const dt = (e.timeStamp - dr.lastT) / 1000;\n        if (dt > 0.001) {\n          dr.v = dr.v * 0.6 + ((p - dr.lastPos) / dt) * 0.4;\n          dr.lastPos = p;\n          dr.lastT = e.timeStamp;\n        }\n        E.pos = p;\n        E.target = p;\n        E.vel = 0;\n        E.wake();\n        return;\n      }\n    }\n    if (e.pointerType === \"touch\" || E.reduced || !stage) return;\n    const rect = stage.getBoundingClientRect();\n    const front = cardEls.current[E.active]?.getBoundingClientRect();\n    E.pxT = clamp(((e.clientX - rect.left) / rect.width) * 2 - 1, -1, 1);\n    E.pyT = clamp(((e.clientY - rect.top) / rect.height) * 2 - 1, -1, 1);\n    if (front && front.width) {\n      stage.style.setProperty(\"--mx\", `${(((e.clientX - front.left) / front.width) * 100).toFixed(1)}%`);\n      stage.style.setProperty(\"--my\", `${(((e.clientY - front.top) / front.height) * 100).toFixed(1)}%`);\n    }\n    E.glareT = 1;\n    E.wake();\n  };\n\n  const endPointer = (e: PointerEvent<HTMLDivElement>) => {\n    const E = eng.current;\n    const dr = E.drag;\n    if (!dr || dr.id !== e.pointerId) return;\n    E.drag = null;\n    if (!dr.moved) return;\n    E.dragging = false;\n    E.justDragged = true;\n    window.setTimeout(() => {\n      E.justDragged = false;\n    }, 60);\n    const v = e.type === \"pointercancel\" || e.timeStamp - dr.lastT > 90 ? 0 : clamp(dr.v, -9, 9);\n    let t = Math.round(E.pos + v * THROW);\n    if (!E.loop) t = clamp(t, 0, Math.max(0, E.n - 1));\n    E.target = t;\n    E.vel = v;\n    E.wake();\n  };\n\n  const onPointerLeave = (e: PointerEvent<HTMLDivElement>) => {\n    const E = eng.current;\n    if (e.pointerType === \"touch\") return;\n    E.glareT = 0;\n    E.pxT = 0;\n    E.pyT = 0;\n    E.wake();\n  };\n\n  const onCardClick = (i: number) => {\n    const E = eng.current;\n    if (E.justDragged) return;\n    goTo(E, i);\n  };\n\n  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {\n    const E = eng.current;\n    if (e.altKey || e.ctrlKey || e.metaKey) return;\n    if (e.key === \"ArrowRight\" || e.key === \"PageDown\") step(E, 1);\n    else if (e.key === \"ArrowLeft\" || e.key === \"PageUp\") step(E, -1);\n    else if (e.key === \"Home\") goTo(E, 0);\n    else if (e.key === \"End\") goTo(E, n - 1);\n    else return;\n    e.preventDefault();\n  };\n\n  const wrapD = (d: number) => (looping ? d - n * Math.round(d / n) : d);\n  const dots = n <= 7;\n\n  return (\n    <div\n      ref={rootRef}\n      role=\"group\"\n      aria-roledescription=\"carousel\"\n      aria-label={label}\n      onKeyDown={onKeyDown}\n      className={`relative flex w-full select-none flex-col items-center gap-7 overflow-x-clip ${className}`}\n      style={{ containerType: \"inline-size\" }}\n    >\n      <div\n        ref={stageRef}\n        onPointerDown={onPointerDown}\n        onPointerMove={onPointerMove}\n        onPointerUp={endPointer}\n        onPointerCancel={endPointer}\n        onPointerLeave={onPointerLeave}\n        className=\"relative w-full cursor-grab active:cursor-grabbing\"\n        style={\n          {\n            \"--cc-w\": \"var(--cc3d-card-w, clamp(150px, 44cqw, 280px))\",\n            height: \"calc(var(--cc-w) * 1.3)\",\n            perspective: \"calc(var(--cc-w) * 3.6)\",\n            perspectiveOrigin: \"50% 42%\",\n            touchAction: \"pan-y\",\n            overscrollBehaviorX: \"contain\",\n          } as CSSProperties\n        }\n      >\n        {cards.map((card, i) => {\n          const isActive = i === active;\n          const nearby = !isActive && Math.abs(wrapD(i - active)) <= 1;\n          const P = pose(wrapD(i - initial), n, looping);\n          return (\n            <div\n              key={i}\n              ref={(el) => {\n                cardEls.current[i] = el;\n              }}\n              role={isActive ? \"group\" : \"button\"}\n              aria-roledescription={isActive ? \"slide\" : undefined}\n              aria-label={isActive ? `${card}, ${i + 1} of ${n}` : `Show card: ${card}`}\n              aria-hidden={!isActive && !nearby ? true : undefined}\n              tabIndex={isActive || nearby ? 0 : -1}\n              onClick={isActive ? undefined : () => onCardClick(i)}\n              onKeyDown={\n                isActive\n                  ? undefined\n                  : (e) => {\n                      if (e.key === \"Enter\" || e.key === \" \") {\n                        e.preventDefault();\n                        e.stopPropagation();\n                        goTo(eng.current, i);\n                      }\n                    }\n              }\n              className={`absolute top-0 ${RING} focus-visible:!rounded-[calc(var(--cc-w)*0.08)] ${isActive ? \"\" : \"cursor-pointer\"}`}\n              style={\n                {\n                  left: \"50%\",\n                  width: \"var(--cc-w)\",\n                  height: \"100%\",\n                  marginLeft: \"calc(var(--cc-w) / -2)\",\n                  borderRadius: \"calc(var(--cc-w) * 0.08)\",\n                  boxShadow: \"0 38px 60px -30px rgba(0,0,0,0.7), 0 14px 26px -14px rgba(0,0,0,0.45)\",\n                  willChange: \"transform\",\n                  transform: P.transform,\n                  opacity: P.opacity,\n                  zIndex: P.zIndex,\n                  visibility: P.visibility,\n                  \"--dim\": P.dim,\n                  \"--sheen\": P.sheen,\n                  \"--focus\": P.focus,\n                } as CSSProperties\n              }\n            >\n              <div\n                ref={(el) => {\n                  faceEls.current[i] = el;\n                }}\n                className=\"absolute inset-0 overflow-hidden\"\n                style={{ borderRadius: \"inherit\", background: \"#0b0c10\", filter: P.filter }}\n              >\n                {renderCard ? (\n                  <div className=\"absolute inset-0\">{renderCard(card, i, isActive)}</div>\n                ) : (\n                  <DefaultFace title={card} index={i} total={n} uid={`${uid}c${i}`} />\n                )}\n                <div\n                  aria-hidden\n                  className=\"pointer-events-none absolute inset-0\"\n                  style={{ background: \"linear-gradient(105deg, transparent calc(var(--sheen) - 24%), rgba(255,255,255,0.09) var(--sheen), transparent calc(var(--sheen) + 24%))\" }}\n                />\n                <div\n                  aria-hidden\n                  className=\"pointer-events-none absolute inset-0\"\n                  style={{\n                    background: \"radial-gradient(circle at var(--mx, 50%) var(--my, 30%), rgba(255,255,255,0.24), transparent 55%)\",\n                    opacity: \"calc(var(--glare, 0) * var(--focus, 1))\",\n                  }}\n                />\n                <div aria-hidden className=\"pointer-events-none absolute inset-0\" style={{ background: \"#05060a\", opacity: \"var(--dim, 0)\" }} />\n                <div\n                  aria-hidden\n                  className=\"pointer-events-none absolute inset-0\"\n                  style={{ borderRadius: \"inherit\", boxShadow: \"inset 0 0 0 1px rgba(255,255,255,0.13), inset 0 1px 0 rgba(255,255,255,0.28)\" }}\n                />\n              </div>\n            </div>\n          );\n        })}\n      </div>\n\n      <div className=\"flex items-center justify-center gap-1\">\n        <button\n          type=\"button\"\n          aria-label=\"Previous card\"\n          disabled={!looping && active <= 0}\n          onClick={() => step(eng.current, -1)}\n          className={`${BTN} ${RING}`}\n          style={{ boxShadow: \"inset 0 0 0 1px color-mix(in srgb, currentColor 28%, transparent)\" }}\n        >\n          <svg aria-hidden viewBox=\"0 0 16 16\" width=\"16\" height=\"16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.7\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n            <path d=\"M10 3 5 8l5 5\" />\n          </svg>\n        </button>\n        {dots ? (\n          <div role=\"group\" aria-label=\"Choose card\" className=\"flex items-center px-1\">\n            {cards.map((card, i) => (\n              <button\n                key={i}\n                type=\"button\"\n                aria-label={`Go to card ${i + 1}: ${card}`}\n                aria-current={i === active ? \"true\" : undefined}\n                onClick={() => goTo(eng.current, i)}\n                className={`group flex h-10 w-7 cursor-pointer items-center justify-center bg-transparent focus-visible:!rounded-full ${RING}`}\n              >\n                <span\n                  className=\"block h-1.5 rounded-full transition-[width,opacity] duration-300 ease-out group-hover:!opacity-80 motion-reduce:transition-none\"\n                  style={{ width: i === active ? 20 : 6, background: \"currentColor\", opacity: i === active ? 1 : 0.32 }}\n                />\n              </button>\n            ))}\n          </div>\n        ) : (\n          <span className=\"min-w-[8ch] px-2 text-center text-xs tabular-nums tracking-[0.18em] opacity-60\" aria-hidden>\n            {String(active + 1).padStart(2, \"0\")} / {String(n).padStart(2, \"0\")}\n          </span>\n        )}\n        <button\n          type=\"button\"\n          aria-label=\"Next card\"\n          disabled={!looping && active >= n - 1}\n          onClick={() => step(eng.current, 1)}\n          className={`${BTN} ${RING}`}\n          style={{ boxShadow: \"inset 0 0 0 1px color-mix(in srgb, currentColor 28%, transparent)\" }}\n        >\n          <svg aria-hidden viewBox=\"0 0 16 16\" width=\"16\" height=\"16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.7\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n            <path d=\"m6 3 5 5-5 5\" />\n          </svg>\n        </button>\n      </div>\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {n > 0 ? `${cards[active] ?? \"\"}, ${active + 1} of ${n}` : \"\"}\n      </span>\n    </div>\n  );\n}\n\n/** Move the target one card (wraps when looping, stops at the ends otherwise). */\nfunction step(E: Engine, dir: number) {\n  if (E.n < 2) return;\n  const t = Math.round(E.target) + dir;\n  E.target = E.loop ? t : clamp(t, 0, E.n - 1);\n  E.wake();\n}\n\n/** Move the target to card i by the shortest way round. */\nfunction goTo(E: Engine, i: number) {\n  if (E.n < 2) return;\n  const base = Math.round(E.target);\n  if (E.loop) {\n    let d = mod(i, E.n) - mod(base, E.n);\n    d -= E.n * Math.round(d / E.n);\n    E.target = base + d;\n  } else {\n    E.target = clamp(i, 0, E.n - 1);\n  }\n  E.wake();\n}\n","type":"registry:component","target":"components/viberdy/card-carousel-3d.tsx"}],"meta":{"tier":"free","tags":["carousel","3d","coverflow","cards","drag","swipe","perspective","spring","slider"],"href":"https://viberdy.dev/library/card-carousel-3d","aiPrompt":"Create a React + Tailwind (v3.4 with the container-queries plugin, or v4) component named CardCarousel3D in one self-contained \"use client\" file. React only, no animation library, no icon library (inline SVG chevrons). It is a coverflow carousel: cards on an arc, the front one facing you, neighbours turned toward it and receding with dim + blur.\n\nProps (all optional): cards = [\"Design\", \"Build\", \"Ship\", \"Iterate\"] (titles), renderCard(card, index, active) (replaces the built-in face), defaultIndex = 0, onChange(index), loop = true (wraps; needs 3+ cards, otherwise clamps with rubber-band ends and disabled arrows), label = \"Card carousel\", className (merged on the root).\n\nModel. One continuous number pos says which card is in front (pos 2.4 = between card 2 and 3). Keep it with a target and velocity in a mutable engine object held in a useRef (initialised with useRef(makeEngine(...))), never read refs during render. For card i the signed distance is d = i - pos, wrapped to the shortest way round when looping. A single requestAnimationFrame loop (started on demand, sleeping when settled, with the handle reset to 0 in cleanup) steps a spring toward the target (stiffness 150, damping 23, substeps of 1/120 s, dt clamped to 50 ms) and writes every card's pose straight to the DOM (transform, opacity, z-index, visibility, plus CSS variables --dim, --sheen, --focus). React renders the same pose once as the initial inline style so the first paint is correct.\n\nPose, with a = |d|, s = sign(d), near = min(a,1), far = min(max(a-1,0),2.5), all lengths in card widths W via a CSS variable --cc-w:\n- x = s*(near*0.74 + far*0.36); z = -(near*0.42 + far*0.2); rotateY = -s*near*46deg; scale = 1 - near*0.04 - far*0.05\n- opacity 1 until a=1.4, then falls linearly to 0.56 at 2.2, then to 0 at 3.2; when looping multiply by clamp((n/2 - a)/0.7, 0, 1) so the card that wraps past the back fades out unseen. visibility hidden at opacity <= 0.01.\n- face blur = min(a,2.2)*1.15 px (filter on the face element, none below 0.05px); a dark overlay of opacity near*0.3 + far*0.1 dims it; a diagonal sheen band at (50 - d*40)% sweeps across as cards slide; z-index = 1000 - round(a*100).\n- transform: translate3d(calc(var(--cc-w) * x), 0, calc(var(--cc-w) * z)) rotateY(...) scale(...).\n\nLayout. Root: flex w-full flex-col items-center gap-7 select-none overflow-x-clip, container-type inline-size, role=\"group\" aria-roledescription=\"carousel\" aria-label. Stage: relative w-full, --cc-w: var(--cc3d-card-w, clamp(150px, 44cqw, 280px)), height calc(var(--cc-w)*1.3), perspective calc(var(--cc-w)*3.6), perspective-origin 50% 42%, touch-action pan-y, overscroll-behavior-x contain, cursor grab. Cards: absolute, left 50%, top 0, width var(--cc-w), height 100%, margin-left calc(var(--cc-w)/-2), radius calc(var(--cc-w)*0.08), shadow 0 38px 60px -30px rgba(0,0,0,.7) + 0 14px 26px -14px rgba(0,0,0,.45), will-change transform. Cards are NOT preserve-3d; ordering is by z-index. The face (overflow hidden, radius inherit, #0b0c10) holds the art, then overlays: sheen, pointer glare (radial gradient at --mx/--my, opacity glare*focus), dim, and a 1px inset hairline + 1px top highlight.\n\nDefault face (paints its own colours; six palettes cycling, four SVG art variants cycling): soft radial glows, then art (concentric rings with a glowing orb / sweeping gradient arcs / stacked rounded bars rotated -14deg / a crescent made with an SVG mask), a dark bottom fade, a top row with the two-digit index (ui-monospace, 0.16em tracking) and a small glass circle with an arrow, and a title at the bottom (font-size 0.13*W, weight 600, tracking -0.035em, leading 1.04) over a hairline and \"01 / 04\". Make svg ids unique with useId() stripped to alphanumerics.\n\nInteraction.\n- Pointer drag on the stage: after 5 layout px of travel (convert with stage.offsetWidth / rect.width) the press becomes a drag, setPointerCapture; pos = base - dx/(W*0.74) (loop off: rubber band past the ends, 0.55*(1-exp(-1.4x))); track velocity in cards/s as an EMA (0.6/0.4). On release project target = round(pos + clamp(v,-9,9)*0.17), clamp when not looping, carry v into the spring; a stale (>90 ms) or cancelled release has v=0. A click that follows a drag is ignored for 60 ms.\n- Click/tap a side card: move the target there by the shortest way. Enter/Space on a focused side card does the same.\n- Mouse/pen hover over the stage: glare opacity eases to 1 and --mx/--my follow the pointer over the front card; perspective-origin leans up to 7%/5% toward the pointer (eased with 1-exp(-9dt)). Off on touch and reduced motion.\n- Horizontal wheel/trackpad swipe (native non-passive listener, only when |deltaX| > 1.2|deltaY|): one step per gesture (accumulate 36px, re-arm after a 140 ms gap).\n- Keyboard on the root: ArrowRight/PageDown next, ArrowLeft/PageUp previous, Home, End; focus moves to the new front card if it was on a card.\n- Controls under the stage: 40px round previous/next buttons (inset 1px ring in currentColor at 28%, hover tint, press scale .9, disabled when not looping at an end), between them dots (28px wide x 40px tall hit areas; the active dot is a 20px pill) or, past 7 cards, a \"03 / 12\" counter. Controls inherit currentColor so the piece works on light and dark pages; only the cards are dark.\n\nA11y: front card role=\"group\" aria-roledescription=\"slide\" aria-label \"Title, 2 of 4\", tabIndex 0; its immediate neighbours role=\"button\" aria-label \"Show card: Title\" tabIndex 0; further cards aria-hidden and tabIndex -1; a sr-only polite live region announces the front card. Focus rings: focus-visible:!outline-2 focus-visible:!outline-offset-2 focus-visible:!outline-[#5b9bff] with !rounded on the card so a global :focus-visible radius cannot square it. prefers-reduced-motion (matchMedia in an effect, listen for change): no spring (pos = target), no glare, no parallax. With the dots' width transition use motion-reduce:transition-none.","license":"https://viberdy.dev/license"}}