{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "card-shuffle-stack",
  "title": "Card Shuffle Stack",
  "description": "A loose pile of photo cards you shuffle through: throw the top card aside and it tucks in under the stack, bring the bottom one back on top, with drag and flick physics, buttons, arrow keys, optional autoplay and a reduced-motion fallback.",
  "dependencies": [
    "motion",
    "lucide-react",
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/card-shuffle-stack/card-shuffle-stack.tsx",
      "content": "\"use client\";\n/* eslint-disable @next/next/no-img-element -- Registry components work in any React app. */\n\nimport * as React from \"react\";\nimport { animate, motion, useMotionValue, useReducedMotion, useTransform } from \"motion/react\";\nimport { ArrowLeft, ArrowRight } from \"lucide-react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport interface ShuffleCard {\n  id: string;\n  image: string;\n  imageAlt?: string;\n  title: string;\n  subtitle?: string;\n  /** Small mono detail on the right of the caption, e.g. a city. */\n  meta?: string;\n}\n\nexport type CardShuffleTheme = \"dark\" | \"light\";\n\nexport interface CardShuffleStackProps extends Omit<React.ComponentPropsWithoutRef<\"section\">, \"children\" | \"onChange\"> {\n  cards?: ShuffleCard[];\n  /** How many cards peek out behind the top one. */\n  visibleDepth?: number;\n  /** Advance on its own every n ms; pauses on hover, focus and drag. 0 turns it off. */\n  autoPlay?: number;\n  showControls?: boolean;\n  /** Width / height of each card. */\n  aspectRatio?: number;\n  radius?: number;\n  theme?: CardShuffleTheme;\n  label?: string;\n  onChange?: (card: ShuffleCard, index: number) => void;\n  onCardClick?: (card: ShuffleCard) => void;\n}\n\nconst CARDS: ShuffleCard[] = [\n  { id: \"ines\", image: \"/demo/44.webp\", title: \"Inès Moreau\", subtitle: \"Creative director\", meta: \"Paris\" },\n  { id: \"teo\", image: \"/demo/43.webp\", title: \"Teo Varga\", subtitle: \"Set designer\", meta: \"Budapest\" },\n  { id: \"lena\", image: \"/demo/39.webp\", title: \"Lena Brandt\", subtitle: \"Photographer\", meta: \"Berlin\" },\n  { id: \"kai\", image: \"/demo/42.webp\", title: \"Kai Nakamura\", subtitle: \"Colourist\", meta: \"Tokyo\" },\n  { id: \"noor\", image: \"/demo/22.webp\", title: \"Noor Haddad\", subtitle: \"Producer\", meta: \"Lisbon\" },\n  { id: \"marco\", image: \"/demo/36.webp\", title: \"Marco Ferri\", subtitle: \"Lighting\", meta: \"Milan\" },\n];\n\n// Resting pose for each depth behind the top card: a little higher, smaller and turned, like a loose pile.\nconst TILTS = [0, -4, 3.5, -2.5, 2];\nconst EASE = [0.22, 1, 0.36, 1] as const;\n\nfunction pose(depth: number, visibleDepth: number) {\n  const d = Math.min(depth, visibleDepth + 1);\n  return {\n    x: d === 0 ? 0 : (d % 2 ? -1 : 1) * d * 6,\n    y: -d * 16,\n    scale: 1 - d * 0.055,\n    rotate: TILTS[d % TILTS.length],\n    opacity: depth > visibleDepth ? 0 : 1,\n  };\n}\n\ntype Move = { id: string; dir: 1 | -1; phase: \"out\" | \"in\" } | null;\n\nexport function CardShuffleStack({\n  cards = CARDS,\n  visibleDepth = 3,\n  autoPlay = 0,\n  showControls = true,\n  aspectRatio = 4 / 5,\n  radius = 20,\n  theme = \"dark\",\n  label = \"Team\",\n  onChange,\n  onCardClick,\n  className,\n  style,\n  ...props\n}: CardShuffleStackProps) {\n  const reduce = useReducedMotion();\n  const [order, setOrder] = React.useState(() => cards.map((card) => card.id));\n  const [move, setMove] = React.useState<Move>(null);\n  // Autoplay waits while the pointer is over the stack, while it has focus, and while a card is held.\n  const [hovering, setHovering] = React.useState(false);\n  const [focused, setFocused] = React.useState(false);\n  const [holding, setHolding] = React.useState(false);\n  const paused = hovering || focused || holding;\n  const stageRef = React.useRef<HTMLDivElement>(null);\n  const dragX = useMotionValue(0);\n  const dragY = useMotionValue(0);\n  const dragRotate = useTransform(dragX, [-260, 260], [-12, 12]);\n  const drag = React.useRef<{ x: number; y: number; t: number; vx: number; lastX: number; lastT: number; moved: boolean } | null>(null);\n  const light = theme === \"light\";\n\n  // Keep the order in step with the cards prop (adding or removing cards).\n  const ids = cards.map((card) => card.id).join(\"|\");\n  const [prevIds, setPrevIds] = React.useState(ids);\n  if (ids !== prevIds) {\n    setPrevIds(ids);\n    setOrder((prev) => [...prev.filter((id) => cards.some((c) => c.id === id)), ...cards.map((c) => c.id).filter((id) => !prev.includes(id))]);\n  }\n\n  const byId = React.useMemo(() => new Map(cards.map((card) => [card.id, card])), [cards]);\n  const top = byId.get(order[0]);\n  const topIndex = top ? cards.indexOf(top) : 0;\n  // Only the throw itself blocks input; once a card has been re-stacked and is springing home, the next\n  // press can start straight away, so quick taps are never dropped.\n  const busy = move?.phase === \"out\";\n\n  const width = () => stageRef.current?.offsetWidth ?? 300;\n\n  const announce = React.useCallback(\n    (nextOrder: string[]) => {\n      const card = byId.get(nextOrder[0]);\n      if (card) onChange?.(card, cards.indexOf(card));\n    },\n    [byId, cards, onChange],\n  );\n\n  /** Top card out to the side, then under the pile. */\n  const next = React.useCallback(\n    (dir: 1 | -1 = -1) => {\n      if (busy || order.length < 2) return;\n      if (reduce) {\n        const nextOrder = [...order.slice(1), order[0]];\n        setOrder(nextOrder);\n        announce(nextOrder);\n        return;\n      }\n      setMove({ id: order[0], dir, phase: \"out\" });\n    },\n    [busy, order, reduce, announce],\n  );\n\n  /** Bottom card out from under the pile, then onto the top. */\n  const prev = React.useCallback(() => {\n    if (busy || order.length < 2) return;\n    const last = order[order.length - 1];\n    if (reduce) {\n      const nextOrder = [last, ...order.slice(0, -1)];\n      setOrder(nextOrder);\n      announce(nextOrder);\n      return;\n    }\n    setMove({ id: last, dir: 1, phase: \"out\" });\n  }, [busy, order, reduce, announce]);\n\n  const settle = (id: string) => {\n    if (!move || move.id !== id) return;\n    if (move.phase === \"out\") {\n      // Halfway: re-stack. A leaving top card drops to the back; a returning bottom card jumps to the front.\n      const leavingTop = order[0] === id;\n      const nextOrder = leavingTop ? [...order.slice(1), id] : [id, ...order.filter((x) => x !== id)];\n      setOrder(nextOrder);\n      setMove({ ...move, phase: \"in\" });\n      announce(nextOrder);\n    } else setMove(null);\n  };\n\n  React.useEffect(() => {\n    if (!autoPlay || paused || reduce || cards.length < 2) return;\n    const timer = window.setInterval(() => next(-1), Math.max(1200, autoPlay));\n    return () => window.clearInterval(timer);\n  }, [autoPlay, paused, reduce, cards.length, next]);\n\n  const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {\n    if (busy || event.button !== 0 || (event.target as HTMLElement).closest(\"button,a\")) return;\n    event.currentTarget.setPointerCapture(event.pointerId);\n    const now = performance.now();\n    drag.current = { x: event.clientX, y: event.clientY, t: now, vx: 0, lastX: event.clientX, lastT: now, moved: false };\n    setHolding(true);\n  };\n  const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {\n    const d = drag.current;\n    if (!d) return;\n    const now = performance.now();\n    const dx = event.clientX - d.x;\n    if (Math.abs(dx) > 4) d.moved = true;\n    d.vx = ((event.clientX - d.lastX) / Math.max(1, now - d.lastT)) * 1000;\n    d.lastX = event.clientX;\n    d.lastT = now;\n    dragX.set(dx);\n    dragY.set((event.clientY - d.y) * 0.25);\n  };\n  const onPointerUp = () => {\n    const d = drag.current;\n    drag.current = null;\n    setHolding(false);\n    if (!d) return;\n    const dx = dragX.get();\n    const flung = Math.abs(dx) > width() * 0.28 || Math.abs(d.vx) > 650;\n    // Either way the drag offset springs home; when the card is thrown, the pose animation carries it out.\n    if (flung) next(dx < 0 ? -1 : 1);\n    animate(dragX, 0, { type: \"spring\", stiffness: 380, damping: 32 });\n    animate(dragY, 0, { type: \"spring\", stiffness: 380, damping: 32 });\n    if (!d.moved && top) onCardClick?.(top);\n  };\n\n  const palette = {\n    \"--cs-ink\": light ? \"#141414\" : \"#f4f4f2\",\n    \"--cs-muted\": light ? \"#6b6b6b\" : \"#8f8f8f\",\n    \"--cs-line\": light ? \"#dcdcd8\" : \"#2a2a2a\",\n    \"--cs-chip\": light ? \"#ffffff\" : \"#161616\",\n  } as React.CSSProperties;\n\n  return (\n    <section\n      aria-roledescription=\"carousel\"\n      aria-label={label}\n      className={cn(\"flex w-full flex-col items-center\", className)}\n      style={{ ...palette, color: \"var(--cs-ink)\", ...style }}\n      onPointerEnter={(event) => event.pointerType === \"mouse\" && setHovering(true)}\n      onPointerLeave={() => setHovering(false)}\n      onFocus={() => setFocused(true)}\n      onBlur={(event) => !event.currentTarget.contains(event.relatedTarget) && setFocused(false)}\n      onKeyDown={(event) => {\n        if (event.key === \"ArrowRight\") {\n          event.preventDefault();\n          next(-1);\n        } else if (event.key === \"ArrowLeft\") {\n          event.preventDefault();\n          prev();\n        }\n      }}\n      {...props}\n    >\n      <div ref={stageRef} className=\"relative w-full max-w-[320px] touch-pan-y\" style={{ aspectRatio, marginTop: visibleDepth * 16 }}>\n        {cards.map((card) => {\n          const depth = order.indexOf(card.id);\n          const isTop = depth === 0;\n          const moving = move?.id === card.id ? move : null;\n          let target: Record<string, number | string> = pose(depth, visibleDepth);\n          let transition: object = { type: \"spring\", stiffness: 260, damping: 26, mass: 0.9 };\n          if (moving?.phase === \"in\" && depth > visibleDepth) {\n            // Tucking back in: stay visible down to the last visible slot, so the card is seen sliding under the pile.\n            target = { ...pose(visibleDepth, visibleDepth), opacity: 1 };\n          } else if (moving?.phase === \"out\") {\n            // Thrown clear of the pile (percentages are of the card's own size), turning in the direction of travel.\n            target = { x: `${moving.dir * 92}%`, y: \"-8%\", scale: 1, rotate: moving.dir * 14, opacity: 1 };\n            transition = { duration: 0.34, ease: EASE };\n          }\n          // While leaving, the top card stays above everything; a returning bottom card stays below until it's out.\n          const z = moving?.phase === \"out\" ? (order[0] === card.id ? 200 : 0) : 100 - depth;\n          return (\n            <motion.div\n              key={card.id}\n              className=\"absolute inset-0\"\n              style={{ zIndex: z }}\n              initial={false}\n              animate={target}\n              transition={reduce ? { duration: 0 } : transition}\n              onAnimationComplete={() => settle(card.id)}\n              aria-hidden={!isTop}\n            >\n              <motion.div\n                className={cn(\"relative h-full w-full overflow-hidden select-none\", isTop && !busy ? \"cursor-grab active:cursor-grabbing\" : \"\")}\n                style={{\n                  borderRadius: radius,\n                  x: isTop ? dragX : 0,\n                  y: isTop ? dragY : 0,\n                  rotate: isTop ? dragRotate : 0,\n                  background: light ? \"#e6e6e3\" : \"#161616\",\n                  boxShadow: light ? \"0 18px 40px -18px rgba(0,0,0,.35)\" : \"0 24px 50px -20px rgba(0,0,0,.8)\",\n                }}\n                onPointerDown={isTop ? onPointerDown : undefined}\n                onPointerMove={isTop ? onPointerMove : undefined}\n                onPointerUp={isTop ? onPointerUp : undefined}\n                onPointerCancel={isTop ? onPointerUp : undefined}\n              >\n                <img src={card.image} alt={card.imageAlt ?? \"\"} draggable={false} className=\"pointer-events-none absolute inset-0 h-full w-full object-cover\" />\n                <div aria-hidden=\"true\" className=\"absolute inset-0 bg-gradient-to-t from-black/75 via-black/5 to-black/20\" />\n                {/* Cards further back are veiled so the pile reads as depth, not as a row of photos. */}\n                <div aria-hidden=\"true\" className=\"absolute inset-0 bg-black transition-opacity duration-500\" style={{ opacity: Math.min(0.55, depth * 0.16) }} />\n                <span className=\"absolute top-4 left-4 rounded-full bg-black/35 px-2.5 py-1 font-mono text-[10px] text-white backdrop-blur-md\">{String(cards.indexOf(card) + 1).padStart(2, \"0\")}</span>\n                <div className=\"absolute inset-x-0 bottom-0 flex items-end justify-between gap-3 p-5 text-white\">\n                  <div className=\"min-w-0\">\n                    <h3 className=\"truncate text-[20px] leading-tight font-medium tracking-[-0.01em]\">{card.title}</h3>\n                    {card.subtitle && <p className=\"mt-1 text-[12.5px] text-white/70\">{card.subtitle}</p>}\n                  </div>\n                  {card.meta && <span className=\"shrink-0 pb-0.5 font-mono text-[10px] text-white/70\">{card.meta}</span>}\n                </div>\n              </motion.div>\n            </motion.div>\n          );\n        })}\n      </div>\n\n      <p aria-live=\"polite\" className=\"sr-only\">\n        {top ? `${top.title}, ${topIndex + 1} of ${cards.length}` : \"\"}\n      </p>\n\n      {showControls && cards.length > 1 && (\n        <div className=\"mt-8 flex w-full max-w-[320px] items-center justify-between\">\n          <button type=\"button\" aria-label=\"Previous card\" onClick={prev} className=\"flex size-10 cursor-pointer items-center justify-center rounded-full border border-[var(--cs-line)] bg-[var(--cs-chip)] transition-colors hover:border-[var(--cs-muted)] focus-visible:ring-2 focus-visible:ring-[var(--cs-ink)] focus-visible:outline-none\">\n            <ArrowLeft size={16} />\n          </button>\n          <div className=\"flex flex-col items-center gap-2\">\n            <span className=\"font-mono text-[11px] tabular-nums\">\n              {String(topIndex + 1).padStart(2, \"0\")} <span className=\"text-[var(--cs-muted)]\">/ {String(cards.length).padStart(2, \"0\")}</span>\n            </span>\n            <span className=\"flex gap-1\" aria-hidden=\"true\">\n              {cards.map((card, i) => (\n                <span key={card.id} className=\"h-0.5 rounded-full transition-all duration-500\" style={{ width: i === topIndex ? 16 : 6, background: i === topIndex ? \"var(--cs-ink)\" : \"var(--cs-line)\" }} />\n              ))}\n            </span>\n          </div>\n          <button type=\"button\" aria-label=\"Next card\" onClick={() => next(-1)} className=\"flex size-10 cursor-pointer items-center justify-center rounded-full border border-[var(--cs-line)] bg-[var(--cs-chip)] transition-colors hover:border-[var(--cs-muted)] focus-visible:ring-2 focus-visible:ring-[var(--cs-ink)] focus-visible:outline-none\">\n            <ArrowRight size={16} />\n          </button>\n        </div>\n      )}\n    </section>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}