{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "product-spin-viewer",
  "title": "3D Product Spin Viewer",
  "description": "A 360° product viewer driven by an image sequence: drag with inertia, an idle spin, a tick ruler that jumps to any angle, hotspots that fade in on the side they belong to, and pointer-follow zoom, with a hairline loading bar.",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/product-spin-viewer/product-spin-viewer.tsx",
      "content": "\"use client\";\n\nimport * as React from \"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 SpinHotspot {\n  /** View angle (degrees) the hotspot belongs to; it fades in around it. */\n  angle: number;\n  /** Position over the image at that angle, in % of its width and height. */\n  x: number;\n  y: number;\n  label: string;\n  detail?: string;\n}\n\nexport type ProductSpinViewerTheme = \"dark\" | \"light\";\n\nexport interface ProductSpinViewerProps extends Omit<React.ComponentPropsWithoutRef<\"div\">, \"children\" | \"title\"> {\n  /** Image sequence of one full turn, evenly spaced, in turning order. */\n  frames?: string[];\n  theme?: ProductSpinViewerTheme;\n  height?: number;\n  title?: string;\n  subtitle?: string;\n  /** Idle spin in degrees per second; 0 turns it off. */\n  autoSpin?: number;\n  dragSensitivity?: number;\n  /** Keep turning for a moment after a flick. */\n  inertia?: boolean;\n  /** Turn the other way for the same drag. */\n  reverse?: boolean;\n  hotspots?: SpinHotspot[];\n  showRuler?: boolean;\n  showHint?: boolean;\n  enableZoom?: boolean;\n  zoomScale?: number;\n  /** Width / height of the frames. */\n  frameAspect?: number;\n}\n\nconst PALETTES = {\n  dark: {\n    background: \"#080808\",\n    text: \"rgba(255,255,255,0.92)\",\n    muted: \"rgba(255,255,255,0.42)\",\n    tickColor: \"rgba(255,255,255,0.22)\",\n    activeTick: \"#FFFFFF\",\n    shadow: \"radial-gradient(closest-side, rgba(0,0,0,0.85), rgba(0,0,0,0))\",\n    glow: \"radial-gradient(ellipse 50% 45% at 50% 48%, rgba(255,255,255,0.06), rgba(255,255,255,0) 70%)\",\n    dot: \"#FFFFFF\",\n    card: \"rgba(20,20,20,0.92)\",\n    cardBorder: \"rgba(255,255,255,0.12)\",\n    button: \"rgba(255,255,255,0.08)\",\n    buttonHover: \"rgba(255,255,255,0.14)\",\n    emptyText: \"rgba(255,255,255,0.4)\",\n    emptyBorder: \"1.5px dashed rgba(255,255,255,0.15)\",\n  },\n  light: {\n    background: \"#F5F5F3\",\n    text: \"rgba(0,0,0,0.88)\",\n    muted: \"rgba(0,0,0,0.42)\",\n    tickColor: \"rgba(0,0,0,0.18)\",\n    activeTick: \"#000000\",\n    shadow: \"radial-gradient(closest-side, rgba(0,0,0,0.3), rgba(0,0,0,0))\",\n    glow: \"radial-gradient(ellipse 50% 45% at 50% 48%, rgba(255,255,255,0.9), rgba(255,255,255,0) 70%)\",\n    dot: \"#000000\",\n    card: \"rgba(255,255,255,0.94)\",\n    cardBorder: \"rgba(0,0,0,0.1)\",\n    button: \"rgba(0,0,0,0.05)\",\n    buttonHover: \"rgba(0,0,0,0.1)\",\n    emptyText: \"rgba(0,0,0,0.4)\",\n    emptyBorder: \"1.5px dashed rgba(0,0,0,0.15)\",\n  },\n} as const;\n\nconst DEFAULT_FRAMES = Array.from({ length: 48 }, (_, i) => `/demo/spin/camera-${String(i).padStart(2, \"0\")}.webp`);\n\nconst DEFAULT_HOTSPOTS: SpinHotspot[] = [\n  { angle: 0, x: 60, y: 60, label: \"35mm f/2 lens\", detail: \"Seven elements, coated glass\" },\n  { angle: 0, x: 75, y: 13, label: \"Shutter dial\", detail: \"1 s to 1/2000 s\" },\n  { angle: 180, x: 55, y: 52, label: \"3-inch display\", detail: \"Sunlight readable\" },\n];\n\nconst clamp = (v: number, min: number, max: number) => Math.min(Math.max(v, min), max);\nconst wrap360 = (d: number) => ((d % 360) + 360) % 360;\n/** Signed shortest turn from a to b, in degrees. */\nconst turnTo = (a: number, b: number) => ((((b - a) % 360) + 540) % 360) - 180;\n\nexport function ProductSpinViewer({\n  frames = DEFAULT_FRAMES,\n  theme = \"dark\",\n  height = 560,\n  title = \"Field Camera 35\",\n  subtitle = \"Brushed aluminium · Leatherette\",\n  autoSpin = 24,\n  dragSensitivity = 1,\n  inertia = true,\n  reverse = false,\n  hotspots = DEFAULT_HOTSPOTS,\n  showRuler = true,\n  showHint = true,\n  enableZoom = true,\n  zoomScale = 1.9,\n  frameAspect = 1.25,\n  className,\n  ...props\n}: ProductSpinViewerProps) {\n  const palette = PALETTES[theme];\n  const n = frames.length;\n  const step = 360 / Math.max(n, 1);\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const stageRef = React.useRef<HTMLDivElement>(null);\n  const zoomRef = React.useRef<HTMLDivElement>(null);\n  const frameRefs = React.useRef<(HTMLImageElement | null)[]>([]);\n  const tickRefs = React.useRef<(HTMLSpanElement | null)[]>([]);\n  const hotspotRefs = React.useRef<(HTMLDivElement | null)[]>([]);\n  const readoutRef = React.useRef<HTMLSpanElement>(null);\n\n  const [loaded, setLoaded] = React.useState(0);\n  const [touched, setTouched] = React.useState(false);\n  const [zoomed, setZoomed] = React.useState(false);\n  const [openHotspot, setOpenHotspot] = React.useState<number | null>(null);\n  const ready = loaded >= n;\n\n  const spin = React.useRef({ angle: 0, v: 0, target: null as number | null, shown: 0 });\n  const drag = React.useRef({ active: false, moved: false, x: 0, lastT: 0 });\n  const idleSince = React.useRef(0);\n  const wakeRef = React.useRef<() => void>(() => {});\n  const optsRef = React.useRef({ n, step, autoSpin, dragSensitivity, inertia, reverse, ready, zoomed, hotspots, paused: false });\n  React.useEffect(() => {\n    optsRef.current = { n, step, autoSpin, dragSensitivity, inertia, reverse, ready, zoomed, hotspots, paused: openHotspot !== null };\n    wakeRef.current();\n  }, [n, step, autoSpin, dragSensitivity, inertia, reverse, ready, zoomed, hotspots, openHotspot]);\n\n  // Count frames that have loaded (cached images may already be complete before hydration).\n  React.useEffect(() => {\n    let count = 0;\n    const done = new Set<number>();\n    const mark = (i: number) => {\n      if (done.has(i)) return;\n      done.add(i);\n      count++;\n      setLoaded(count);\n    };\n    const cleanups: (() => void)[] = [];\n    frameRefs.current.forEach((img, i) => {\n      if (!img) return;\n      if (img.complete && img.naturalWidth) mark(i);\n      else {\n        const on = () => mark(i);\n        img.addEventListener(\"load\", on);\n        img.addEventListener(\"error\", on);\n        cleanups.push(() => {\n          img.removeEventListener(\"load\", on);\n          img.removeEventListener(\"error\", on);\n        });\n      }\n    });\n    return () => cleanups.forEach((c) => c());\n  }, [frames]);\n\n  React.useEffect(() => {\n    let raf: number | null = null;\n    let last = 0;\n    let inView = true;\n    const paint = () => {\n      const { n, step, hotspots } = optsRef.current;\n      const s = spin.current;\n      const idx = ((Math.round(s.angle / step) % n) + n) % n;\n      if (idx !== s.shown) {\n        const prev = frameRefs.current[s.shown];\n        const next = frameRefs.current[idx];\n        if (prev) prev.style.opacity = \"0\";\n        if (next) next.style.opacity = \"1\";\n        const pt = tickRefs.current[s.shown];\n        const nt = tickRefs.current[idx];\n        if (pt) pt.removeAttribute(\"data-active\");\n        if (nt) nt.setAttribute(\"data-active\", \"\");\n        s.shown = idx;\n      }\n      if (readoutRef.current) readoutRef.current.textContent = `${String(Math.round(wrap360(s.angle)) % 360).padStart(3, \"0\")}°`;\n      // Hotspots fade in within 28° of their angle and drift sideways as the product turns away.\n      hotspots.forEach((h, i) => {\n        const el = hotspotRefs.current[i];\n        if (!el) return;\n        const d = turnTo(h.angle, s.angle);\n        const o = clamp(1 - Math.abs(d) / 28, 0, 1);\n        el.style.opacity = o.toFixed(3);\n        el.style.visibility = o < 0.02 ? \"hidden\" : \"visible\";\n        el.style.left = `${(50 + (h.x - 50) * Math.cos((d * Math.PI) / 180)).toFixed(2)}%`;\n      });\n    };\n    const tick = (now: number) => {\n      const dt = last ? Math.min((now - last) / 1000, 0.05) : 1 / 60;\n      last = now;\n      const { autoSpin, ready, zoomed, paused } = optsRef.current;\n      const s = spin.current;\n      const d = drag.current;\n      if (s.target !== null) {\n        const diff = s.target - s.angle;\n        s.angle += diff * (1 - Math.pow(0.002, dt));\n        if (Math.abs(diff) < 0.2) {\n          s.angle = s.target;\n          s.target = null;\n          idleSince.current = now;\n        }\n      } else if (!d.active) {\n        s.angle += s.v * dt;\n        s.v *= Math.pow(0.08, dt);\n        if (Math.abs(s.v) < 2) s.v = 0;\n        if (autoSpin && ready && !zoomed && !paused && s.v === 0 && now - idleSince.current > 2500) s.angle += autoSpin * dt;\n      }\n      paint();\n      const busy = d.active || s.target !== null || s.v !== 0 || (autoSpin && ready && !zoomed && !paused);\n      raf = inView && busy ? requestAnimationFrame(tick) : null;\n      if (raf === null) last = 0;\n    };\n    wakeRef.current = () => {\n      if (raf === null && inView) raf = requestAnimationFrame(tick);\n    };\n    paint();\n    raf = requestAnimationFrame(tick);\n    const observer = new IntersectionObserver(([entry]) => {\n      inView = entry.isIntersecting;\n      if (inView) wakeRef.current();\n    });\n    if (rootRef.current) observer.observe(rootRef.current);\n    return () => {\n      if (raf) cancelAnimationFrame(raf);\n      observer.disconnect();\n    };\n  }, []);\n\n  const goTo = React.useCallback((deg: number) => {\n    const s = spin.current;\n    s.v = 0;\n    s.target = s.angle + turnTo(s.angle, deg);\n    setTouched(true);\n    wakeRef.current();\n  }, []);\n\n  // Drag to turn (or, zoomed in, to look around); a tap toggles zoom.\n  React.useEffect(() => {\n    const el = stageRef.current;\n    if (!el) return;\n    const setOrigin = (e: PointerEvent) => {\n      const zoom = zoomRef.current;\n      if (!zoom) return;\n      const r = el.getBoundingClientRect();\n      zoom.style.transformOrigin = `${clamp(((e.clientX - r.left) / r.width) * 100, 0, 100).toFixed(1)}% ${clamp(((e.clientY - r.top) / r.height) * 100, 0, 100).toFixed(1)}%`;\n    };\n    const onDown = (e: PointerEvent) => {\n      if (e.button !== 0 || (e.target as HTMLElement).closest(\"button\")) return;\n      drag.current = { active: true, moved: false, x: e.clientX, lastT: e.timeStamp };\n      spin.current.v = 0;\n      spin.current.target = null;\n      el.setPointerCapture(e.pointerId);\n      wakeRef.current();\n    };\n    const onMove = (e: PointerEvent) => {\n      if (optsRef.current.zoomed) {\n        if (e.pointerType === \"mouse\" || drag.current.active) setOrigin(e);\n        return;\n      }\n      const d = drag.current;\n      if (!d.active) return;\n      const dx = e.clientX - d.x;\n      if (!d.moved && Math.abs(dx) < 4) return;\n      if (!d.moved) {\n        d.moved = true;\n        el.style.cursor = \"grabbing\";\n        setTouched(true);\n      }\n      const { dragSensitivity, reverse } = optsRef.current;\n      // One stage width of drag is a bit more than a full turn.\n      const perPx = (400 / el.clientWidth) * dragSensitivity * (reverse ? -1 : 1);\n      spin.current.angle += dx * perPx;\n      const dt = Math.max((e.timeStamp - d.lastT) / 1000, 0.008);\n      spin.current.v = spin.current.v * 0.5 + ((dx * perPx) / dt) * 0.5;\n      d.x = e.clientX;\n      d.lastT = e.timeStamp;\n      wakeRef.current();\n    };\n    const onUp = (e: PointerEvent) => {\n      const d = drag.current;\n      if (!d.active) return;\n      d.active = false;\n      el.style.cursor = \"\";\n      idleSince.current = performance.now();\n      if (!optsRef.current.inertia || e.timeStamp - d.lastT > 80) spin.current.v = 0;\n      if (!d.moved && enableZoom) {\n        setOrigin(e);\n        setZoomed((z) => !z);\n        setTouched(true);\n      }\n      wakeRef.current();\n    };\n    el.addEventListener(\"pointerdown\", onDown);\n    el.addEventListener(\"pointermove\", onMove);\n    el.addEventListener(\"pointerup\", onUp);\n    el.addEventListener(\"pointercancel\", onUp);\n    return () => {\n      el.removeEventListener(\"pointerdown\", onDown);\n      el.removeEventListener(\"pointermove\", onMove);\n      el.removeEventListener(\"pointerup\", onUp);\n      el.removeEventListener(\"pointercancel\", onUp);\n    };\n  }, [enableZoom]);\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    const s = spin.current;\n    if (e.key === \"ArrowRight\") goTo(Math.round((s.target ?? s.angle) / step) * step + step);\n    else if (e.key === \"ArrowLeft\") goTo(Math.round((s.target ?? s.angle) / step) * step - step);\n    else if (e.key === \"Home\") goTo(0);\n    else if (e.key === \"Escape\" && zoomed) setZoomed(false);\n    else if ((e.key === \"Enter\" || e.key === \" \") && enableZoom && e.target === e.currentTarget) setZoomed((z) => !z);\n    else return;\n    e.preventDefault();\n  };\n\n  if (n === 0) {\n    return (\n      <div className={cn(\"flex h-full w-full items-center justify-center rounded-xl\", className)} style={{ minHeight: 300, background: palette.background, border: palette.emptyBorder }} {...props}>\n        <span className=\"text-center text-sm leading-[1.6]\" style={{ color: palette.emptyText }}>\n          Add frames\n        </span>\n      </div>\n    );\n  }\n\n  const ticks = Array.from({ length: n }, (_, i) => i);\n\n  return (\n    <div\n      ref={rootRef}\n      className={cn(\"relative w-full overflow-hidden outline-none select-none\", className)}\n      style={{ height, background: palette.background }}\n      tabIndex={0}\n      role=\"region\"\n      aria-roledescription=\"360 degree product viewer\"\n      aria-label={`${title}. Drag or use the arrow keys to turn it${enableZoom ? \", Enter to zoom\" : \"\"}.`}\n      onKeyDown={onKeyDown}\n      {...props}\n    >\n      <div className=\"pointer-events-none absolute inset-0\" style={{ background: palette.glow }} />\n\n      {(title || subtitle) && (\n        <div className=\"pointer-events-none absolute top-5 left-5 z-10 sm:top-7 sm:left-8\">\n          {title && (\n            <div className=\"text-[15px]\" style={{ color: palette.text }}>\n              {title}\n            </div>\n          )}\n          {subtitle && (\n            <div className=\"mt-1 text-[10px] tracking-[0.2em] uppercase\" style={{ color: palette.muted }}>\n              {subtitle}\n            </div>\n          )}\n        </div>\n      )}\n\n      {enableZoom && (\n        <button\n          type=\"button\"\n          onClick={() => {\n            setZoomed((z) => !z);\n            setTouched(true);\n          }}\n          aria-label={zoomed ? \"Zoom out\" : \"Zoom in\"}\n          aria-pressed={zoomed}\n          className=\"absolute top-5 right-5 z-10 flex h-9 w-9 cursor-pointer items-center justify-center rounded-full border-0 text-[18px] leading-none transition-colors sm:top-7 sm:right-8\"\n          style={{ background: palette.button, color: palette.text }}\n          onMouseEnter={(e) => (e.currentTarget.style.background = palette.buttonHover)}\n          onMouseLeave={(e) => (e.currentTarget.style.background = palette.button)}\n        >\n          {zoomed ? \"−\" : \"+\"}\n        </button>\n      )}\n\n      <div ref={stageRef} className=\"absolute inset-x-0 top-[9%] bottom-[19%] touch-pan-y [container-type:size]\" style={{ cursor: zoomed ? \"zoom-out\" : \"grab\" }}>\n        <div\n          ref={zoomRef}\n          className=\"absolute inset-0 transition-transform duration-500\"\n          style={{ transform: zoomed ? `scale(${zoomScale})` : \"scale(1)\", transitionTimingFunction: \"cubic-bezier(0.22,1,0.36,1)\" }}\n        >\n          {/* The frames' own box, contained in the stage, so hotspot percentages land on the product. */}\n          <div className=\"absolute inset-0 m-auto\" style={{ width: `min(100cqw, ${(frameAspect * 100).toFixed(2)}cqh)`, height: `min(100cqh, ${(100 / frameAspect).toFixed(2)}cqw)` }}>\n            <div className=\"absolute inset-x-[16%] bottom-[9.5%] h-[8%]\" style={{ background: palette.shadow }} />\n            {frames.map((src, i) => (\n              <img\n                key={i}\n                ref={(el) => {\n                  frameRefs.current[i] = el;\n                }}\n                src={src}\n                alt={i === 0 ? title || \"Product\" : \"\"}\n                aria-hidden={i === 0 ? undefined : true}\n                draggable={false}\n                decoding=\"async\"\n                className=\"pointer-events-none absolute inset-0 h-full w-full object-contain\"\n                style={{ opacity: i === 0 ? 1 : 0 }}\n              />\n            ))}\n            {hotspots.map((h, i) => {\n              const open = openHotspot === i;\n              return (\n                <div\n                  key={i}\n                  ref={(el) => {\n                    hotspotRefs.current[i] = el;\n                  }}\n                  className=\"absolute\"\n                  style={{\n                    left: `${h.x}%`,\n                    top: `${h.y}%`,\n                    opacity: h.angle === 0 ? 1 : 0,\n                    visibility: h.angle === 0 ? \"visible\" : \"hidden\",\n                    transform: `scale(${zoomed ? 1 / zoomScale : 1})`,\n                    zIndex: open ? 2 : 1,\n                  }}\n                >\n                  <button\n                    type=\"button\"\n                    onClick={() => setOpenHotspot(open ? null : i)}\n                    onMouseEnter={() => setOpenHotspot(i)}\n                    onMouseLeave={() => setOpenHotspot(null)}\n                    onFocus={() => setOpenHotspot(i)}\n                    onBlur={() => setOpenHotspot(null)}\n                    aria-label={h.label}\n                    aria-expanded={open}\n                    className=\"relative -mt-3 -ml-3 flex h-6 w-6 cursor-pointer items-center justify-center rounded-full border-0 bg-transparent p-0\"\n                  >\n                    <span className=\"absolute inset-0 animate-[spin-ping_2.4s_ease-out_infinite] rounded-full\" style={{ boxShadow: `0 0 0 1px ${palette.dot}` }} />\n                    <span className=\"block h-2 w-2 rounded-full\" style={{ background: palette.dot }} />\n                  </button>\n                  <div\n                    role=\"tooltip\"\n                    className=\"pointer-events-none absolute top-1/2 left-4 w-max max-w-[180px] -translate-y-1/2 rounded-[3px] px-3 py-2 transition-[opacity,transform] duration-200\"\n                    style={{ background: palette.card, border: `1px solid ${palette.cardBorder}`, opacity: open ? 1 : 0, transform: `translate(${open ? 0 : -4}px, -50%)` }}\n                  >\n                    <div className=\"text-[12px]\" style={{ color: palette.text }}>\n                      {h.label}\n                    </div>\n                    {h.detail && (\n                      <div className=\"mt-0.5 text-[10.5px]\" style={{ color: palette.muted }}>\n                        {h.detail}\n                      </div>\n                    )}\n                  </div>\n                </div>\n              );\n            })}\n          </div>\n        </div>\n      </div>\n\n      <div className=\"absolute inset-x-0 bottom-5 z-10 flex flex-col items-center gap-3 sm:bottom-7\">\n        {showHint && (\n          <div\n            className=\"pointer-events-none flex items-center gap-2.5 text-[10px] tracking-[0.2em] uppercase transition-opacity duration-700\"\n            style={{ color: palette.muted, opacity: touched || !ready ? 0 : 1 }}\n          >\n            <span className=\"h-px w-5\" style={{ background: palette.tickColor }} />\n            Drag to turn\n            <span className=\"h-px w-5\" style={{ background: palette.tickColor }} />\n          </div>\n        )}\n        {showRuler && (\n          <div className=\"flex items-end gap-4\">\n            <div className=\"relative flex items-end\" role=\"group\" aria-label=\"Viewing angle\">\n              {ticks.map((i) => (\n                <button\n                  key={i}\n                  type=\"button\"\n                  tabIndex={-1}\n                  onClick={() => goTo(i * step)}\n                  aria-label={`Turn to ${Math.round(i * step)}°`}\n                  className=\"group/tick flex h-6 cursor-pointer items-end justify-center border-0 bg-transparent p-0\"\n                  style={{ width: n > 60 ? 4 : 6 }}\n                >\n                  <span\n                    ref={(el) => {\n                      tickRefs.current[i] = el;\n                    }}\n                    data-active={i === 0 ? \"\" : undefined}\n                    className=\"block w-px transition-[height,background-color] duration-200 data-[active]:!h-5 data-[active]:!bg-[var(--spin-active)] group-hover/tick:h-3.5\"\n                    style={{ height: i % 6 === 0 ? 11 : 7, background: palette.tickColor, [\"--spin-active\" as string]: palette.activeTick }}\n                  />\n                </button>\n              ))}\n              {!ready && (\n                <span className=\"pointer-events-none absolute -bottom-1 left-0 h-px transition-[width] duration-200\" style={{ width: `${(loaded / n) * 100}%`, background: palette.activeTick }} />\n              )}\n            </div>\n            <span ref={readoutRef} className=\"w-9 text-[10px] tracking-[0.12em] tabular-nums\" style={{ color: palette.muted }}>\n              000°\n            </span>\n          </div>\n        )}\n        <span className=\"sr-only\" aria-live=\"polite\">\n          {ready ? \"\" : `Loading ${loaded} of ${n} views`}\n        </span>\n      </div>\n\n      <style>{`@keyframes spin-ping { 0% { transform: scale(0.6); opacity: 0.9; } 80%, 100% { transform: scale(1.6); opacity: 0; } }`}</style>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}