{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "scratch-card",
  "title": "Scratch Card",
  "description": "A foil scratch-off card. Rub the foil away with a finger or cursor to reveal what is underneath, with a scratch texture that follows your speed, foil flakes, and a soft chime when the rest lifts off.",
  "dependencies": [
    "@rexa-developer/tiks",
    "motion",
    "web-haptics"
  ],
  "files": [
    {
      "path": "src/registry/components/scratch-card/scratch-card.tsx",
      "content": "\"use client\";\n\nimport { useTiks } from \"@rexa-developer/tiks/react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n\ttype ComponentProps,\n\ttype KeyboardEvent,\n\ttype PointerEvent,\n\ttype ReactNode,\n\ttype Ref,\n\tuseEffect,\n\tuseImperativeHandle,\n\tuseLayoutEffect,\n\tuseRef,\n\tuseState,\n} from \"react\";\nimport { useWebHaptics } from \"web-haptics/react\";\nimport { cn } from \"@/lib/utils\";\n\n/** Columns and rows of the coverage grid; each cell is cleared at most once. */\nconst GRID_COLUMNS = 40;\nconst GRID_ROWS = 24;\n/** Brush radius as a fraction of the card width, clamped to px limits. */\nconst BRUSH_FRACTION = 0.06;\nconst MIN_BRUSH_PX = 14;\nconst MAX_BRUSH_PX = 30;\n/** Distance between brush dabs, as a fraction of the radius. */\nconst DAB_SPACING = 0.2;\n/** A grid cell is cleared once a dab center passes this close, as a fraction of the radius. */\nconst CLEAR_REACH = 0.8;\n/** Px scratched over foil between haptic ticks. */\nconst HAPTIC_STEP_PX = 44;\n/** Minimum ms between haptic ticks. */\nconst CUE_THROTTLE_MS = 35;\n/** Minimum ms between scratch sound grains. */\nconst GRAIN_INTERVAL_MS = 28;\n/** Length of one scratch sound grain, in seconds. */\nconst GRAIN_SECONDS = 0.07;\n/** Below this pointer speed, in px/ms, the scratch is silent. */\nconst SILENT_SPEED = 0.03;\n/** A stroke still counts as scratching foil this many ms after it last cleared a cell. */\nconst FRESH_MS = 90;\n/** Px scratched over foil per flake, and the most flakes alive at once. */\nconst FLAKE_STEP_PX = 9;\nconst MAX_FLAKES = 24;\n/** Canvas backing store limit, in device px per CSS px. */\nconst MAX_BACKING_SCALE = 4;\n/** Resting sheen position along the gradient, and how far the pointer moves it. */\nconst SHEEN_REST = 0.42;\nconst SHEEN_PARALLAX = 0.14;\nconst GRADIENT_ANGLE = 115;\nconst CORNER_RADIUS = 16;\n\nconst revealEase = [0.23, 1, 0.32, 1] as const;\nconst REVEAL_SECONDS = 0.35;\n\n// Two soft sine notes, a fifth apart (tiks' success cue).\nconst CHIME_SOUND = {\n\tname: \"scratch-card-chime\",\n\tbaseFreq: 587,\n\tnoiseColor: \"pink\",\n\toscType: \"sine\",\n\tfilterFreq: 3000,\n\tfilterQ: 1,\n\tattack: 0.006,\n\tdecay: 3.2,\n\tbrightness: 2000,\n} as const;\n\ntype FoilName = \"silver\" | \"gold\" | \"graphite\";\n\ninterface FoilPalette {\n\t/** Base gradient stops, laid along `GRADIENT_ANGLE`. */\n\tstops: string[];\n\t/** Peak opacity of the brushed streaks and the fine grain. */\n\tstreak: number;\n\tgrain: number;\n\tsheen: string;\n\t/** Engraved hint: the cut is `ink`, its lower lip catches `highlight`. */\n\tink: string;\n\thighlight: string;\n\t/** Colors for the specks that pop off the brush. */\n\tflakes: string[];\n}\n\nconst foils: Record<FoilName, FoilPalette> = {\n\tsilver: {\n\t\tstops: [\"#f3f4f6\", \"#cdd1d7\", \"#eceef1\", \"#b9bec6\", \"#e3e6ea\", \"#c4c9d0\"],\n\t\tstreak: 0.04,\n\t\tgrain: 0.03,\n\t\tsheen: \"rgb(255 255 255 / 0.5)\",\n\t\tink: \"rgb(72 78 88 / 0.5)\",\n\t\thighlight: \"rgb(255 255 255 / 0.75)\",\n\t\tflakes: [\"#e6e8ec\", \"#c2c7ce\", \"#f7f8fa\", \"#aab0b9\"],\n\t},\n\tgold: {\n\t\tstops: [\"#f6e7bd\", \"#d9b56c\", \"#f3dfa8\", \"#c39a4c\", \"#ecd18f\", \"#cfa85e\"],\n\t\tstreak: 0.045,\n\t\tgrain: 0.03,\n\t\tsheen: \"rgb(255 249 230 / 0.6)\",\n\t\tink: \"rgb(110 76 22 / 0.5)\",\n\t\thighlight: \"rgb(255 246 220 / 0.7)\",\n\t\tflakes: [\"#f1dca2\", \"#d2ab5f\", \"#f8ebc6\", \"#b98f42\"],\n\t},\n\tgraphite: {\n\t\tstops: [\"#6b7078\", \"#43474e\", \"#5e636b\", \"#363a40\", \"#555a62\", \"#3d4148\"],\n\t\tstreak: 0.05,\n\t\tgrain: 0.045,\n\t\tsheen: \"rgb(255 255 255 / 0.16)\",\n\t\tink: \"rgb(12 13 16 / 0.78)\",\n\t\thighlight: \"rgb(255 255 255 / 0.2)\",\n\t\tflakes: [\"#73787f\", \"#4a4e55\", \"#878c93\", \"#3a3e44\"],\n\t},\n};\n\nfunction cssGradient(palette: FoilPalette) {\n\treturn `linear-gradient(${GRADIENT_ANGLE}deg, ${palette.stops.join(\", \")})`;\n}\n\nfunction clamp(value: number, min: number, max: number) {\n\treturn Math.min(Math.max(value, min), max);\n}\n\n/** A small seeded random generator, so the foil texture is the same every render. */\nfunction seededRandom(seed: number) {\n\tlet state = seed >>> 0;\n\treturn () => {\n\t\tstate = (state + 0x6d2b79f5) >>> 0;\n\t\tlet t = state;\n\t\tt = Math.imul(t ^ (t >>> 15), t | 1);\n\t\tt ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n\t\treturn ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n\t};\n}\n\n/** End points of a CSS-style linear gradient line at `angle` across a `width` by `height` box. */\nfunction gradientLine(width: number, height: number, angle: number) {\n\tconst radians = (angle * Math.PI) / 180;\n\tconst dx = Math.sin(radians);\n\tconst dy = -Math.cos(radians);\n\tconst half = (Math.abs(width * dx) + Math.abs(height * dy)) / 2;\n\treturn {\n\t\tx0: width / 2 - dx * half,\n\t\ty0: height / 2 - dy * half,\n\t\tx1: width / 2 + dx * half,\n\t\ty1: height / 2 + dy * half,\n\t};\n}\n\nfunction createCanvas(width: number, height: number) {\n\tconst canvas = document.createElement(\"canvas\");\n\tcanvas.width = Math.max(1, width);\n\tcanvas.height = Math.max(1, height);\n\treturn canvas;\n}\n\n/** Paints the foil artwork (no sheen) at `scale` device px per CSS px. */\nfunction paintFoil(\n\tcanvas: HTMLCanvasElement,\n\twidth: number,\n\theight: number,\n\tscale: number,\n\tpalette: FoilPalette,\n\thint: string,\n\tfontFamily: string,\n) {\n\tconst ctx = canvas.getContext(\"2d\");\n\tif (!ctx) return;\n\tconst random = seededRandom(0x5c7a7c4);\n\tctx.setTransform(scale, 0, 0, scale, 0, 0);\n\tctx.globalCompositeOperation = \"source-over\";\n\tctx.globalAlpha = 1;\n\n\tconst line = gradientLine(width, height, GRADIENT_ANGLE);\n\tconst base = ctx.createLinearGradient(line.x0, line.y0, line.x1, line.y1);\n\tpalette.stops.forEach((stop, index) => {\n\t\tbase.addColorStop(index / (palette.stops.length - 1), stop);\n\t});\n\tctx.fillStyle = base;\n\tctx.fillRect(0, 0, width, height);\n\n\t// Brushed metal: thin horizontal streaks of varying length, one device px tall.\n\tctx.setTransform(1, 0, 0, 1, 0, 0);\n\tconst deviceWidth = canvas.width;\n\tconst deviceHeight = canvas.height;\n\tconst streaks = Math.round(deviceHeight * 1.6);\n\tfor (let index = 0; index < streaks; index++) {\n\t\tconst light = random() > 0.45;\n\t\tctx.fillStyle = light ? \"#fff\" : \"#000\";\n\t\tctx.globalAlpha = palette.streak * (0.25 + random() * 0.75);\n\t\tconst length = deviceWidth * (0.2 + random() * 0.9);\n\t\tconst x = random() * (deviceWidth + length) - length;\n\t\tconst y = Math.floor(random() * deviceHeight);\n\t\tctx.fillRect(x, y, length, Math.max(1, Math.round(scale / 2)));\n\t}\n\n\t// Fine grain, about half a CSS px per speck so it stays visible at 3x and 4x.\n\tconst speck = Math.max(1, Math.round(scale / 2));\n\tconst tileSize = 64 * speck;\n\tconst tile = createCanvas(tileSize, tileSize);\n\tconst tileCtx = tile.getContext(\"2d\");\n\tif (tileCtx) {\n\t\tconst pixels = tileCtx.createImageData(tileSize, tileSize);\n\t\tconst data = pixels.data;\n\t\tfor (let y = 0; y < tileSize; y += speck) {\n\t\t\tfor (let x = 0; x < tileSize; x += speck) {\n\t\t\t\tconst shade = random() > 0.5 ? 255 : 0;\n\t\t\t\tconst alpha = Math.round(random() * random() * palette.grain * 255 * 2);\n\t\t\t\tfor (let sy = 0; sy < speck; sy++) {\n\t\t\t\t\tfor (let sx = 0; sx < speck; sx++) {\n\t\t\t\t\t\tconst offset = ((y + sy) * tileSize + x + sx) * 4;\n\t\t\t\t\t\tdata[offset] = shade;\n\t\t\t\t\t\tdata[offset + 1] = shade;\n\t\t\t\t\t\tdata[offset + 2] = shade;\n\t\t\t\t\t\tdata[offset + 3] = alpha;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttileCtx.putImageData(pixels, 0, 0);\n\t\tconst pattern = ctx.createPattern(tile, \"repeat\");\n\t\tif (pattern) {\n\t\t\tctx.globalAlpha = 1;\n\t\t\tctx.fillStyle = pattern;\n\t\t\tctx.fillRect(0, 0, deviceWidth, deviceHeight);\n\t\t}\n\t}\n\n\tctx.setTransform(scale, 0, 0, scale, 0, 0);\n\tctx.globalAlpha = 1;\n\n\t// A soft bevel: the top edge catches light and the bottom edge falls off.\n\tconst bevel = ctx.createLinearGradient(0, 0, 0, height);\n\tbevel.addColorStop(0, \"rgb(255 255 255 / 0.55)\");\n\tbevel.addColorStop(0.5, \"rgb(255 255 255 / 0)\");\n\tbevel.addColorStop(0.5, \"rgb(0 0 0 / 0)\");\n\tbevel.addColorStop(1, \"rgb(0 0 0 / 0.14)\");\n\tctx.strokeStyle = bevel;\n\tctx.lineWidth = 1;\n\tctx.beginPath();\n\tctx.roundRect(0.5, 0.5, width - 1, height - 1, CORNER_RADIUS - 0.5);\n\tctx.stroke();\n\n\t// The engraved hint, flanked by two hairlines.\n\tconst label = hint.trim().toLocaleUpperCase();\n\tif (!label) return;\n\tconst fontSize = clamp(width * 0.042, 10, 14);\n\tctx.font = `600 ${fontSize}px ${fontFamily}`;\n\tctx.letterSpacing = `${(fontSize * 0.18).toFixed(2)}px`;\n\tctx.textAlign = \"center\";\n\tctx.textBaseline = \"middle\";\n\tconst textWidth = Math.min(ctx.measureText(label).width, width * 0.7);\n\tconst centerX = width / 2;\n\tconst centerY = height / 2;\n\tconst rule = clamp(width * 0.07, 10, 26);\n\tconst gap = fontSize * 0.9;\n\tconst engrave = (color: string, offset: number) => {\n\t\tctx.fillStyle = color;\n\t\tctx.fillText(\n\t\t\tlabel,\n\t\t\tcenterX + fontSize * 0.09,\n\t\t\tcenterY + offset,\n\t\t\twidth * 0.7,\n\t\t);\n\t\tconst left = centerX - textWidth / 2 - gap;\n\t\tconst right = centerX + textWidth / 2 + gap;\n\t\tctx.fillRect(left - rule, centerY + offset - 0.5, rule, 1);\n\t\tctx.fillRect(right, centerY + offset - 0.5, rule, 1);\n\t};\n\tengrave(palette.highlight, 0.75);\n\tengrave(palette.ink, 0);\n}\n\n/** A soft round dab: solid in the middle, feathered to nothing at the radius. */\nfunction createBrush(radius: number, scale: number) {\n\tconst size = Math.ceil(radius * 2 * scale);\n\tconst brush = createCanvas(size, size);\n\tconst ctx = brush.getContext(\"2d\");\n\tif (!ctx) return brush;\n\tconst center = size / 2;\n\tconst gradient = ctx.createRadialGradient(\n\t\tcenter,\n\t\tcenter,\n\t\t0,\n\t\tcenter,\n\t\tcenter,\n\t\tcenter,\n\t);\n\tgradient.addColorStop(0, \"rgb(0 0 0 / 1)\");\n\tgradient.addColorStop(0.7, \"rgb(0 0 0 / 1)\");\n\tgradient.addColorStop(0.86, \"rgb(0 0 0 / 0.6)\");\n\tgradient.addColorStop(1, \"rgb(0 0 0 / 0)\");\n\tctx.fillStyle = gradient;\n\tctx.fillRect(0, 0, size, size);\n\treturn brush;\n}\n\n/** Squared distance from a point to the segment `a`→`b`. */\nfunction distanceToSegmentSq(\n\tpx: number,\n\tpy: number,\n\tax: number,\n\tay: number,\n\tbx: number,\n\tby: number,\n) {\n\tconst dx = bx - ax;\n\tconst dy = by - ay;\n\tconst lengthSq = dx * dx + dy * dy;\n\tconst t =\n\t\tlengthSq > 0\n\t\t\t? clamp(((px - ax) * dx + (py - ay) * dy) / lengthSq, 0, 1)\n\t\t\t: 0;\n\tconst x = ax + dx * t - px;\n\tconst y = ay + dy * t - py;\n\treturn x * x + y * y;\n}\n\ninterface ScratchAudio {\n\tctx: AudioContext;\n\toutput: GainNode;\n\tnoise: AudioBuffer;\n}\n\nlet scratchAudio: ScratchAudio | null = null;\n\n/** One shared context for every card, created on the first scratch (a user gesture). */\nfunction getScratchAudio() {\n\tif (scratchAudio && scratchAudio.ctx.state !== \"closed\") return scratchAudio;\n\tconst AudioContextClass =\n\t\twindow.AudioContext ??\n\t\t(window as unknown as { webkitAudioContext?: typeof AudioContext })\n\t\t\t.webkitAudioContext;\n\tif (!AudioContextClass) return null;\n\tconst ctx = new AudioContextClass();\n\tconst output = ctx.createGain();\n\toutput.gain.value = 0.8;\n\toutput.connect(ctx.destination);\n\t// Grainy noise with sparse louder crackles, like foil catching under a nail.\n\tconst noise = ctx.createBuffer(1, ctx.sampleRate, ctx.sampleRate);\n\tconst data = noise.getChannelData(0);\n\tfor (let index = 0; index < data.length; index++) {\n\t\tconst crackle = Math.random() < 0.035 ? 1 : 0.4;\n\t\tdata[index] = (Math.random() * 2 - 1) * crackle;\n\t}\n\tscratchAudio = { ctx, output, noise };\n\treturn scratchAudio;\n}\n\n/** Plays one short burst of filtered noise. Starts and ends at zero gain, so it never clicks. */\nfunction playScratchGrain(\n\taudio: ScratchAudio,\n\tloudness: number,\n\tbrightness: number,\n) {\n\tconst { ctx } = audio;\n\tif (ctx.state === \"suspended\") void ctx.resume().catch(() => {});\n\tconst start = ctx.currentTime + 0.005;\n\tconst source = ctx.createBufferSource();\n\tsource.buffer = audio.noise;\n\tconst band = ctx.createBiquadFilter();\n\tband.type = \"bandpass\";\n\tband.frequency.value = 1500 + brightness * 4500;\n\tband.Q.value = 0.9;\n\tconst highpass = ctx.createBiquadFilter();\n\thighpass.type = \"highpass\";\n\thighpass.frequency.value = 700;\n\tconst gain = ctx.createGain();\n\tconst peak = loudness * (0.75 + Math.random() * 0.5);\n\tgain.gain.setValueAtTime(0, start);\n\tgain.gain.linearRampToValueAtTime(peak, start + GRAIN_SECONDS * 0.25);\n\tgain.gain.linearRampToValueAtTime(0, start + GRAIN_SECONDS);\n\tsource.connect(band);\n\tband.connect(highpass);\n\thighpass.connect(gain);\n\tgain.connect(audio.output);\n\tconst offset = Math.random() * (audio.noise.duration - GRAIN_SECONDS - 0.02);\n\tsource.start(start, offset, GRAIN_SECONDS + 0.01);\n}\n\ninterface Flake {\n\tx: number;\n\ty: number;\n\tvx: number;\n\tvy: number;\n\tangle: number;\n\tspin: number;\n\twidth: number;\n\theight: number;\n\tage: number;\n\tlife: number;\n\tcolor: string;\n}\n\ninterface Stroke {\n\tpointerId: number;\n\tx: number;\n\ty: number;\n\ttime: number;\n\t/** Smoothed pointer speed, in px/ms. */\n\tspeed: number;\n\t/** Converts client px to the card's layout px (accounts for CSS transforms and zoom). */\n\tleft: number;\n\ttop: number;\n\tratioX: number;\n\tratioY: number;\n\tfreshAt: number;\n\thapticDistance: number;\n\tflakeDistance: number;\n\tlastGrainAt: number;\n}\n\nexport interface ScratchCardHandle {\n\t/** Puts a fresh foil back over the content. Silent. */\n\treset: () => void;\n\t/** Reveals the content at once, as if scratched clear. Silent. */\n\treveal: () => void;\n}\n\nexport interface ScratchCardProps\n\textends Omit<ComponentProps<\"div\">, \"children\" | \"onProgress\" | \"ref\"> {\n\t/** The content under the foil. Hidden from assistive technology until revealed. */\n\tchildren?: ReactNode;\n\t/** Fraction of the foil, 0 to 1, that has to be cleared before the rest lifts off. */\n\tthreshold?: number;\n\t/** The foil finish. */\n\tfoil?: FoilName;\n\t/** Engraved into the foil, and scratched away with it. */\n\thint?: string;\n\t/** Called once, when the card is revealed by scratching, the button, a key, or `reveal()`. */\n\tonReveal?: () => void;\n\t/** Called with the cleared fraction, 0 to 1, as the foil is scratched. */\n\tonProgress?: (fraction: number) => void;\n\tdisabled?: boolean;\n\t/** Play a scratch texture that follows the pointer speed, and a chime on reveal. */\n\tsound?: boolean;\n\t/** Trigger haptics on supported devices. */\n\thaptics?: boolean;\n\t/** Exposes `reset()` and `reveal()`. */\n\tref?: Ref<ScratchCardHandle>;\n}\n\nexport function ScratchCard({\n\tchildren,\n\tthreshold = 0.6,\n\tfoil = \"silver\",\n\thint = \"Scratch here\",\n\tonReveal,\n\tonProgress,\n\tdisabled = false,\n\tsound = true,\n\thaptics = true,\n\tclassName,\n\tref,\n\t\"aria-label\": ariaLabel,\n\t\"aria-labelledby\": ariaLabelledBy,\n\t...props\n}: ScratchCardProps) {\n\tconst [revealed, setRevealed] = useState(false);\n\tconst palette = foils[foil] ?? foils.silver;\n\n\tconst reducedMotion = useReducedMotion() ?? false;\n\tconst { trigger: haptic } = useWebHaptics();\n\t// Sound stays on under reduced motion; only movement is reduced.\n\tconst { success: playChime } = useTiks({\n\t\ttheme: CHIME_SOUND,\n\t\trespectReducedMotion: false,\n\t});\n\n\tconst rootRef = useRef<HTMLDivElement>(null);\n\tconst foilRef = useRef<HTMLDivElement>(null);\n\tconst fallbackRef = useRef<HTMLDivElement>(null);\n\tconst canvasRef = useRef<HTMLCanvasElement>(null);\n\tconst contentRef = useRef<HTMLDivElement>(null);\n\n\tconst sizeRef = useRef({ width: 0, height: 0, scale: 0 });\n\tconst baseRef = useRef<HTMLCanvasElement | null>(null);\n\tconst maskRef = useRef<HTMLCanvasElement | null>(null);\n\tconst brushRef = useRef<HTMLCanvasElement | null>(null);\n\tconst gridRef = useRef(new Uint8Array(GRID_COLUMNS * GRID_ROWS));\n\tconst clearedRef = useRef(0);\n\tconst progressRef = useRef(0);\n\tconst revealedRef = useRef(false);\n\tconst strokeRef = useRef<Stroke | null>(null);\n\tconst flakesRef = useRef<Flake[]>([]);\n\tconst sheenRef = useRef({ value: SHEEN_REST, target: SHEEN_REST });\n\tconst frameRef = useRef(0);\n\tconst lastFrameRef = useRef<number | null>(null);\n\tconst lastHapticAtRef = useRef(Number.NEGATIVE_INFINITY);\n\tconst focusContentRef = useRef(false);\n\n\t// Event handlers and the frame loop read the latest props through refs.\n\tconst latest = useRef({\n\t\tthreshold,\n\t\tpalette,\n\t\thint,\n\t\tonReveal,\n\t\tonProgress,\n\t\tdisabled,\n\t\tsound,\n\t\thaptics,\n\t\treducedMotion,\n\t});\n\tuseLayoutEffect(() => {\n\t\tlatest.current = {\n\t\t\tthreshold,\n\t\t\tpalette,\n\t\t\thint,\n\t\t\tonReveal,\n\t\t\tonProgress,\n\t\t\tdisabled,\n\t\t\tsound,\n\t\t\thaptics,\n\t\t\treducedMotion,\n\t\t};\n\t});\n\n\tconst brushRadius = () =>\n\t\tclamp(sizeRef.current.width * BRUSH_FRACTION, MIN_BRUSH_PX, MAX_BRUSH_PX);\n\n\tconst silent = () =>\n\t\ttypeof document !== \"undefined\" && document.visibilityState === \"hidden\";\n\n\tconst composite = () => {\n\t\tconst canvas = canvasRef.current;\n\t\tconst base = baseRef.current;\n\t\tconst mask = maskRef.current;\n\t\tif (!canvas || !base || !mask) return;\n\t\tconst ctx = canvas.getContext(\"2d\");\n\t\tif (!ctx) return;\n\t\tconst { width, height, scale } = sizeRef.current;\n\t\tctx.setTransform(1, 0, 0, 1, 0, 0);\n\t\tctx.globalAlpha = 1;\n\t\tctx.globalCompositeOperation = \"copy\";\n\t\tctx.drawImage(base, 0, 0);\n\n\t\t// A diagonal sheen across the foil that drifts a little with the pointer.\n\t\tctx.globalCompositeOperation = \"source-over\";\n\t\tctx.setTransform(scale, 0, 0, scale, 0, 0);\n\t\tconst line = gradientLine(width, height, GRADIENT_ANGLE);\n\t\tconst sheen = ctx.createLinearGradient(line.x0, line.y0, line.x1, line.y1);\n\t\tconst at = sheenRef.current.value;\n\t\tsheen.addColorStop(clamp(at - 0.2, 0, 1), \"rgb(255 255 255 / 0)\");\n\t\tsheen.addColorStop(clamp(at, 0, 1), latest.current.palette.sheen);\n\t\tsheen.addColorStop(clamp(at + 0.2, 0, 1), \"rgb(255 255 255 / 0)\");\n\t\tctx.fillStyle = sheen;\n\t\tctx.fillRect(0, 0, width, height);\n\n\t\t// Cut the scratched areas out of the foil and its sheen.\n\t\tctx.setTransform(1, 0, 0, 1, 0, 0);\n\t\tctx.globalCompositeOperation = \"destination-in\";\n\t\tctx.drawImage(mask, 0, 0);\n\n\t\tctx.globalCompositeOperation = \"source-over\";\n\t\tfor (const flake of flakesRef.current) {\n\t\t\tconst cos = Math.cos(flake.angle) * scale;\n\t\t\tconst sin = Math.sin(flake.angle) * scale;\n\t\t\tctx.setTransform(cos, sin, -sin, cos, flake.x * scale, flake.y * scale);\n\t\t\tctx.globalAlpha = 1 - (flake.age / flake.life) ** 2;\n\t\t\tctx.fillStyle = flake.color;\n\t\t\tctx.fillRect(\n\t\t\t\t-flake.width / 2,\n\t\t\t\t-flake.height / 2,\n\t\t\t\tflake.width,\n\t\t\t\tflake.height,\n\t\t\t);\n\t\t}\n\t\tctx.setTransform(1, 0, 0, 1, 0, 0);\n\t\tctx.globalAlpha = 1;\n\t};\n\n\tconst frame = (now: number) => {\n\t\tframeRef.current = 0;\n\t\tconst elapsed =\n\t\t\tlastFrameRef.current === null\n\t\t\t\t? 1 / 60\n\t\t\t\t: Math.min((now - lastFrameRef.current) / 1000, 1 / 20);\n\t\tlastFrameRef.current = now;\n\t\tlet moving = false;\n\n\t\tconst sheen = sheenRef.current;\n\t\tsheen.value +=\n\t\t\t(sheen.target - sheen.value) * (1 - Math.exp(-elapsed / 0.14));\n\t\tif (Math.abs(sheen.target - sheen.value) < 0.0008)\n\t\t\tsheen.value = sheen.target;\n\t\telse moving = true;\n\n\t\tconst flakes = flakesRef.current;\n\t\tfor (let index = flakes.length - 1; index >= 0; index--) {\n\t\t\tconst flake = flakes[index];\n\t\t\tflake.age += elapsed;\n\t\t\tif (flake.age >= flake.life) {\n\t\t\t\tflakes.splice(index, 1);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tflake.vy += 700 * elapsed;\n\t\t\tflake.x += flake.vx * elapsed;\n\t\t\tflake.y += flake.vy * elapsed;\n\t\t\tflake.angle += flake.spin * elapsed;\n\t\t}\n\t\tif (flakes.length) moving = true;\n\n\t\tcomposite();\n\t\tif (moving) wake();\n\t\telse lastFrameRef.current = null;\n\t};\n\n\tconst frameHandlerRef = useRef(frame);\n\tuseLayoutEffect(() => {\n\t\tframeHandlerRef.current = frame;\n\t});\n\n\tfunction wake() {\n\t\tif (frameRef.current) return;\n\t\tframeRef.current = requestAnimationFrame((now) =>\n\t\t\tframeHandlerRef.current(now),\n\t\t);\n\t}\n\n\tuseEffect(() => () => cancelAnimationFrame(frameRef.current), []);\n\n\tconst paintBase = () => {\n\t\tconst { width, height, scale } = sizeRef.current;\n\t\tconst base = baseRef.current;\n\t\tconst root = rootRef.current;\n\t\tif (!base || !root || !width) return;\n\t\tconst fontFamily = getComputedStyle(root).fontFamily || \"sans-serif\";\n\t\tpaintFoil(\n\t\t\tbase,\n\t\t\twidth,\n\t\t\theight,\n\t\t\tscale,\n\t\t\tlatest.current.palette,\n\t\t\tlatest.current.hint,\n\t\t\tfontFamily,\n\t\t);\n\t};\n\n\t/** Sizes the canvases to the card, keeping what was scratched as a fraction of the area. */\n\tconst layout = (force = false) => {\n\t\tconst root = rootRef.current;\n\t\tconst canvas = canvasRef.current;\n\t\tif (!root || !canvas) return;\n\t\tconst width = root.clientWidth;\n\t\tconst height = root.clientHeight;\n\t\tif (!width || !height) return;\n\t\tconst rect = root.getBoundingClientRect();\n\t\tconst zoom = rect.width / width;\n\t\tconst cssZoom =\n\t\t\t(root as HTMLElement & { currentCSSZoom?: number }).currentCSSZoom ?? 1;\n\t\tconst scale = clamp(\n\t\t\twindow.devicePixelRatio * Math.max(zoom, cssZoom, 1e-3),\n\t\t\t1,\n\t\t\tMAX_BACKING_SCALE,\n\t\t);\n\t\tconst current = sizeRef.current;\n\t\tif (\n\t\t\t!force &&\n\t\t\tcurrent.width === width &&\n\t\t\tcurrent.height === height &&\n\t\t\tcurrent.scale === scale &&\n\t\t\tmaskRef.current\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tsizeRef.current = { width, height, scale };\n\t\tconst deviceWidth = Math.round(width * scale);\n\t\tconst deviceHeight = Math.round(height * scale);\n\t\tcanvas.width = deviceWidth;\n\t\tcanvas.height = deviceHeight;\n\n\t\tconst previous = maskRef.current;\n\t\tconst mask = createCanvas(deviceWidth, deviceHeight);\n\t\tconst maskCtx = mask.getContext(\"2d\");\n\t\tif (maskCtx) {\n\t\t\tif (previous) {\n\t\t\t\tmaskCtx.drawImage(previous, 0, 0, deviceWidth, deviceHeight);\n\t\t\t} else {\n\t\t\t\tmaskCtx.fillStyle = \"#000\";\n\t\t\t\tmaskCtx.fillRect(0, 0, deviceWidth, deviceHeight);\n\t\t\t}\n\t\t}\n\t\tmaskRef.current = mask;\n\t\tbaseRef.current = createCanvas(deviceWidth, deviceHeight);\n\t\tbrushRef.current = createBrush(brushRadius(), scale);\n\t\tpaintBase();\n\t\tcomposite();\n\t\tif (fallbackRef.current) fallbackRef.current.hidden = true;\n\t};\n\n\tconst layoutRef = useRef(layout);\n\tuseLayoutEffect(() => {\n\t\tlayoutRef.current = layout;\n\t});\n\n\tconst setProgress = (fraction: number) => {\n\t\tconst rounded = Math.round(fraction * 100) / 100;\n\t\tif (rounded === progressRef.current) return;\n\t\tprogressRef.current = rounded;\n\t\tlatest.current.onProgress?.(rounded);\n\t};\n\n\t/** Clears grid cells along the segment and returns how many were newly cleared. */\n\tconst markSegment = (ax: number, ay: number, bx: number, by: number) => {\n\t\tconst { width, height } = sizeRef.current;\n\t\tconst reach = brushRadius() * CLEAR_REACH;\n\t\tconst reachSq = reach * reach;\n\t\tconst cellWidth = width / GRID_COLUMNS;\n\t\tconst cellHeight = height / GRID_ROWS;\n\t\tconst fromColumn = clamp(\n\t\t\tMath.floor((Math.min(ax, bx) - reach) / cellWidth),\n\t\t\t0,\n\t\t\tGRID_COLUMNS - 1,\n\t\t);\n\t\tconst toColumn = clamp(\n\t\t\tMath.floor((Math.max(ax, bx) + reach) / cellWidth),\n\t\t\t0,\n\t\t\tGRID_COLUMNS - 1,\n\t\t);\n\t\tconst fromRow = clamp(\n\t\t\tMath.floor((Math.min(ay, by) - reach) / cellHeight),\n\t\t\t0,\n\t\t\tGRID_ROWS - 1,\n\t\t);\n\t\tconst toRow = clamp(\n\t\t\tMath.floor((Math.max(ay, by) + reach) / cellHeight),\n\t\t\t0,\n\t\t\tGRID_ROWS - 1,\n\t\t);\n\t\tconst grid = gridRef.current;\n\t\tlet cleared = 0;\n\t\tfor (let row = fromRow; row <= toRow; row++) {\n\t\t\tconst cy = (row + 0.5) * cellHeight;\n\t\t\tfor (let column = fromColumn; column <= toColumn; column++) {\n\t\t\t\tconst cell = row * GRID_COLUMNS + column;\n\t\t\t\tif (grid[cell]) continue;\n\t\t\t\tconst cx = (column + 0.5) * cellWidth;\n\t\t\t\tif (distanceToSegmentSq(cx, cy, ax, ay, bx, by) <= reachSq) {\n\t\t\t\t\tgrid[cell] = 1;\n\t\t\t\t\tcleared++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclearedRef.current += cleared;\n\t\treturn cleared;\n\t};\n\n\t/** Erases the foil along the segment with soft round dabs, spaced so fast flicks leave no gaps. */\n\tconst eraseSegment = (ax: number, ay: number, bx: number, by: number) => {\n\t\tconst mask = maskRef.current;\n\t\tconst brush = brushRef.current;\n\t\tif (!mask || !brush) return;\n\t\tconst ctx = mask.getContext(\"2d\");\n\t\tif (!ctx) return;\n\t\tconst { scale } = sizeRef.current;\n\t\tconst radius = brushRadius();\n\t\tconst distance = Math.hypot(bx - ax, by - ay);\n\t\tconst steps = Math.max(1, Math.ceil(distance / (radius * DAB_SPACING)));\n\t\tctx.globalCompositeOperation = \"destination-out\";\n\t\tfor (let step = 1; step <= steps; step++) {\n\t\t\tconst t = step / steps;\n\t\t\t// A little jitter roughens the edge, like foil flaking rather than a clean cut.\n\t\t\tconst size = radius * (0.92 + Math.random() * 0.16) * 2 * scale;\n\t\t\tconst x =\n\t\t\t\t(ax + (bx - ax) * t) * scale + (Math.random() - 0.5) * 2.4 * scale;\n\t\t\tconst y =\n\t\t\t\t(ay + (by - ay) * t) * scale + (Math.random() - 0.5) * 2.4 * scale;\n\t\t\tctx.drawImage(brush, x - size / 2, y - size / 2, size, size);\n\t\t}\n\t\tctx.globalCompositeOperation = \"source-over\";\n\t};\n\n\tconst spawnFlake = (x: number, y: number, dx: number, dy: number) => {\n\t\tconst flakes = flakesRef.current;\n\t\tif (flakes.length >= MAX_FLAKES) return;\n\t\tconst colors = latest.current.palette.flakes;\n\t\tconst radius = brushRadius();\n\t\tconst length = Math.hypot(dx, dy) || 1;\n\t\t// Specks fly off to either side of the stroke, a little upward.\n\t\tconst side = Math.random() > 0.5 ? 1 : -1;\n\t\tconst speed = 50 + Math.random() * 110;\n\t\tconst normalX = (-dy / length) * side;\n\t\tconst normalY = (dx / length) * side;\n\t\tflakes.push({\n\t\t\tx: x + normalX * radius * 0.6,\n\t\t\ty: y + normalY * radius * 0.6,\n\t\t\tvx: normalX * speed + (dx / length) * 30 + (Math.random() - 0.5) * 40,\n\t\t\tvy: normalY * speed - 70 - Math.random() * 60,\n\t\t\tangle: Math.random() * Math.PI,\n\t\t\tspin: (Math.random() - 0.5) * 18,\n\t\t\twidth: 1.2 + Math.random() * 1.8,\n\t\t\theight: 0.8 + Math.random() * 1.2,\n\t\t\tage: 0,\n\t\t\tlife: 0.35 + Math.random() * 0.3,\n\t\t\tcolor: colors[Math.floor(Math.random() * colors.length)] ?? \"#ccc\",\n\t\t});\n\t};\n\n\tconst endStroke = () => {\n\t\tconst stroke = strokeRef.current;\n\t\tif (!stroke) return;\n\t\tstrokeRef.current = null;\n\t\tconst foilElement = foilRef.current;\n\t\tif (foilElement?.hasPointerCapture(stroke.pointerId)) {\n\t\t\tfoilElement.releasePointerCapture(stroke.pointerId);\n\t\t}\n\t\tif (rootRef.current) delete rootRef.current.dataset.scratching;\n\t};\n\n\t/** Reveals the content; `cue` plays the chime and haptic, for user input only. */\n\tconst reveal = (cue: boolean) => {\n\t\tif (revealedRef.current) return;\n\t\trevealedRef.current = true;\n\t\tendStroke();\n\t\tflakesRef.current = [];\n\t\tsheenRef.current.target = SHEEN_REST;\n\t\tconst root = rootRef.current;\n\t\tfocusContentRef.current = Boolean(\n\t\t\troot && document.activeElement && root.contains(document.activeElement),\n\t\t);\n\t\tsetRevealed(true);\n\t\tprogressRef.current = 1;\n\t\tlatest.current.onProgress?.(1);\n\t\tlatest.current.onReveal?.();\n\t\tif (!cue || silent()) return;\n\t\tif (latest.current.sound) playChime();\n\t\tif (latest.current.haptics) void haptic(\"medium\");\n\t};\n\n\tconst reset = () => {\n\t\tendStroke();\n\t\tgridRef.current.fill(0);\n\t\tclearedRef.current = 0;\n\t\tflakesRef.current = [];\n\t\tsheenRef.current = { value: SHEEN_REST, target: SHEEN_REST };\n\t\tif (progressRef.current !== 0) {\n\t\t\tprogressRef.current = 0;\n\t\t\tlatest.current.onProgress?.(0);\n\t\t}\n\t\tif (revealedRef.current) {\n\t\t\t// The foil remounts, and the layout effect below gives it a fresh mask.\n\t\t\trevealedRef.current = false;\n\t\t\tsetRevealed(false);\n\t\t\treturn;\n\t\t}\n\t\tmaskRef.current = null;\n\t\tlayout(true);\n\t};\n\n\tconst resetRef = useRef(reset);\n\tconst revealRef = useRef(reveal);\n\tuseLayoutEffect(() => {\n\t\tresetRef.current = reset;\n\t\trevealRef.current = reveal;\n\t});\n\n\tuseImperativeHandle(ref, () => ({\n\t\treset: () => resetRef.current(),\n\t\treveal: () => revealRef.current(false),\n\t}));\n\n\t// A fresh foil on mount and after a reset from the revealed state.\n\tuseLayoutEffect(() => {\n\t\tif (revealed) return;\n\t\tmaskRef.current = null;\n\t\tlayoutRef.current(true);\n\t}, [revealed]);\n\n\t// A new finish or hint repaints the foil but keeps what was scratched.\n\t// biome-ignore lint/correctness/useExhaustiveDependencies: repaint when these props change\n\tuseLayoutEffect(() => {\n\t\tif (revealedRef.current || !baseRef.current) return;\n\t\tbrushRef.current = createBrush(brushRadius(), sizeRef.current.scale);\n\t\tpaintBase();\n\t\tcomposite();\n\t}, [foil, hint]);\n\n\tuseEffect(() => {\n\t\tconst root = rootRef.current;\n\t\tif (!root) return;\n\t\tconst observer = new ResizeObserver(() => {\n\t\t\tif (!revealedRef.current) layoutRef.current();\n\t\t});\n\t\tobserver.observe(root);\n\t\t// Repaint once web fonts load so the hint uses the page font.\n\t\tlet active = true;\n\t\tif (document.fonts && document.fonts.status !== \"loaded\") {\n\t\t\tvoid document.fonts.ready.then(() => {\n\t\t\t\tif (active && !revealedRef.current) layoutRef.current(true);\n\t\t\t});\n\t\t}\n\t\treturn () => {\n\t\t\tactive = false;\n\t\t\tobserver.disconnect();\n\t\t};\n\t}, []);\n\n\tuseEffect(() => {\n\t\tif (!revealed || !focusContentRef.current) return;\n\t\tfocusContentRef.current = false;\n\t\tcontentRef.current?.focus({ preventScroll: true });\n\t}, [revealed]);\n\n\tconst endStrokeRef = useRef(endStroke);\n\tuseLayoutEffect(() => {\n\t\tendStrokeRef.current = endStroke;\n\t});\n\n\tuseEffect(() => {\n\t\tif (disabled) endStrokeRef.current();\n\t}, [disabled]);\n\n\t// iOS can still scroll the page under a captured pointer; block it mid-stroke.\n\tuseEffect(() => {\n\t\tconst element = foilRef.current;\n\t\tif (!element || revealed) return;\n\t\tconst onTouchMove = (event: TouchEvent) => {\n\t\t\tif (strokeRef.current) event.preventDefault();\n\t\t};\n\t\telement.addEventListener(\"touchmove\", onTouchMove, { passive: false });\n\t\treturn () => element.removeEventListener(\"touchmove\", onTouchMove);\n\t}, [revealed]);\n\n\tconst scratchTo = (x: number, y: number, time: number) => {\n\t\tconst stroke = strokeRef.current;\n\t\tif (!stroke) return;\n\t\tconst dx = x - stroke.x;\n\t\tconst dy = y - stroke.y;\n\t\tconst distance = Math.hypot(dx, dy);\n\t\tif (distance < 0.5) return;\n\t\tconst elapsed = Math.max(time - stroke.time, 1);\n\t\tstroke.speed = stroke.speed * 0.6 + (distance / elapsed) * 0.4;\n\n\t\teraseSegment(stroke.x, stroke.y, x, y);\n\t\tconst cleared = markSegment(stroke.x, stroke.y, x, y);\n\t\tif (cleared) stroke.freshAt = time;\n\t\tconst onFoil = time - stroke.freshAt < FRESH_MS;\n\t\tconst { sound, haptics, reducedMotion } = latest.current;\n\n\t\tif (onFoil) {\n\t\t\tstroke.hapticDistance += distance;\n\t\t\tif (stroke.hapticDistance >= HAPTIC_STEP_PX) {\n\t\t\t\tstroke.hapticDistance = 0;\n\t\t\t\tif (\n\t\t\t\t\thaptics &&\n\t\t\t\t\t!silent() &&\n\t\t\t\t\ttime - lastHapticAtRef.current >= CUE_THROTTLE_MS\n\t\t\t\t) {\n\t\t\t\t\tlastHapticAtRef.current = time;\n\t\t\t\t\tvoid haptic(\"selection\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!reducedMotion) {\n\t\t\t\tstroke.flakeDistance += distance;\n\t\t\t\twhile (stroke.flakeDistance >= FLAKE_STEP_PX) {\n\t\t\t\t\tstroke.flakeDistance -= FLAKE_STEP_PX;\n\t\t\t\t\tspawnFlake(x, y, dx, dy);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (\n\t\t\tsound &&\n\t\t\tstroke.speed > SILENT_SPEED &&\n\t\t\ttime - stroke.lastGrainAt >= GRAIN_INTERVAL_MS &&\n\t\t\t!silent()\n\t\t) {\n\t\t\tstroke.lastGrainAt = time;\n\t\t\tconst audio = getScratchAudio();\n\t\t\tif (audio) {\n\t\t\t\tconst intensity =\n\t\t\t\t\tclamp((stroke.speed - SILENT_SPEED) / 1.6, 0, 1) ** 0.7;\n\t\t\t\t// Rubbing over cleared card is quieter and duller than over foil.\n\t\t\t\tplayScratchGrain(\n\t\t\t\t\taudio,\n\t\t\t\t\t(0.03 + 0.22 * intensity) * (onFoil ? 1 : 0.3),\n\t\t\t\t\tclamp(stroke.speed / 2.4, 0, 1) * (onFoil ? 1 : 0.4),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tstroke.x = x;\n\t\tstroke.y = y;\n\t\tstroke.time = time;\n\t};\n\n\tconst followSheen = (x: number, y: number) => {\n\t\tif (latest.current.reducedMotion) return;\n\t\tconst { width, height } = sizeRef.current;\n\t\tif (!width || !height) return;\n\t\tsheenRef.current.target =\n\t\t\tSHEEN_REST +\n\t\t\t(x / width - 0.5) * SHEEN_PARALLAX +\n\t\t\t(y / height - 0.5) * SHEEN_PARALLAX * 0.4;\n\t\twake();\n\t};\n\n\tconst toLocal = (clientX: number, clientY: number) => {\n\t\tconst root = rootRef.current;\n\t\tconst rect = root?.getBoundingClientRect();\n\t\tif (!root || !rect?.width || !rect.height) return null;\n\t\treturn {\n\t\t\tx: (clientX - rect.left) * (root.clientWidth / rect.width),\n\t\t\ty: (clientY - rect.top) * (root.clientHeight / rect.height),\n\t\t};\n\t};\n\n\tconst onPointerDown = (event: PointerEvent<HTMLDivElement>) => {\n\t\tif (latest.current.disabled || revealedRef.current) return;\n\t\t// One finger scratches; a second one, or a right click, is ignored.\n\t\tif (!event.isPrimary || strokeRef.current) return;\n\t\tif (event.pointerType === \"mouse\" && event.button !== 0) return;\n\t\tconst root = rootRef.current;\n\t\tconst rect = root?.getBoundingClientRect();\n\t\tif (!root || !rect?.width || !rect.height) return;\n\t\tlayout();\n\t\tevent.currentTarget.setPointerCapture(event.pointerId);\n\t\tconst ratioX = root.clientWidth / rect.width;\n\t\tconst ratioY = root.clientHeight / rect.height;\n\t\tconst x = (event.clientX - rect.left) * ratioX;\n\t\tconst y = (event.clientY - rect.top) * ratioY;\n\t\tstrokeRef.current = {\n\t\t\tpointerId: event.pointerId,\n\t\t\tx,\n\t\t\ty,\n\t\t\ttime: event.timeStamp,\n\t\t\tspeed: 0,\n\t\t\tleft: rect.left,\n\t\t\ttop: rect.top,\n\t\t\tratioX,\n\t\t\tratioY,\n\t\t\tfreshAt: Number.NEGATIVE_INFINITY,\n\t\t\thapticDistance: 0,\n\t\t\tflakeDistance: 0,\n\t\t\tlastGrainAt: Number.NEGATIVE_INFINITY,\n\t\t};\n\t\troot.dataset.scratching = \"\";\n\t\t// Create the audio context inside the gesture so the first grain can play.\n\t\tif (latest.current.sound) getScratchAudio();\n\t\t// A press is a dab.\n\t\teraseSegment(x, y, x, y);\n\t\tif (markSegment(x, y, x, y)) {\n\t\t\tstrokeRef.current.freshAt = event.timeStamp;\n\t\t\tsetProgress(clearedRef.current / gridRef.current.length);\n\t\t}\n\t\tfollowSheen(x, y);\n\t\twake();\n\t};\n\n\tconst onPointerMove = (event: PointerEvent<HTMLDivElement>) => {\n\t\tconst stroke = strokeRef.current;\n\t\tif (!stroke) {\n\t\t\t// Hovering with a mouse tilts the sheen.\n\t\t\tif (event.pointerType === \"mouse\" && !revealedRef.current) {\n\t\t\t\tconst point = toLocal(event.clientX, event.clientY);\n\t\t\t\tif (point) followSheen(point.x, point.y);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (event.pointerId !== stroke.pointerId) return;\n\t\tconst native = event.nativeEvent;\n\t\tconst coalesced = native.getCoalescedEvents?.() ?? [];\n\t\tconst points = coalesced.length ? coalesced : [native];\n\t\tfor (const point of points) {\n\t\t\tconst current = strokeRef.current;\n\t\t\tif (!current) break;\n\t\t\tscratchTo(\n\t\t\t\t(point.clientX - current.left) * current.ratioX,\n\t\t\t\t(point.clientY - current.top) * current.ratioY,\n\t\t\t\tpoint.timeStamp,\n\t\t\t);\n\t\t}\n\t\tconst last = strokeRef.current;\n\t\tif (last) followSheen(last.x, last.y);\n\t\twake();\n\t\tconst fraction = clearedRef.current / gridRef.current.length;\n\t\tsetProgress(fraction);\n\t\tif (fraction >= clamp(latest.current.threshold, 0.05, 1)) reveal(true);\n\t};\n\n\tconst onPointerEnd = (event: PointerEvent<HTMLDivElement>) => {\n\t\tif (strokeRef.current?.pointerId !== event.pointerId) return;\n\t\tendStroke();\n\t};\n\n\tconst onPointerLeave = () => {\n\t\tif (strokeRef.current) return;\n\t\tsheenRef.current.target = SHEEN_REST;\n\t\twake();\n\t};\n\n\tconst onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n\t\tif (latest.current.disabled || revealedRef.current) return;\n\t\tif (event.key !== \"Enter\" && event.key !== \" \") return;\n\t\tevent.preventDefault();\n\t\treveal(true);\n\t};\n\n\tconst transition = {\n\t\tduration: reducedMotion ? 0 : REVEAL_SECONDS,\n\t\tease: revealEase,\n\t};\n\n\treturn (\n\t\t<div\n\t\t\tref={rootRef}\n\t\t\trole=\"group\"\n\t\t\taria-label={ariaLabelledBy ? ariaLabel : (ariaLabel ?? \"Scratch card\")}\n\t\t\taria-labelledby={ariaLabelledBy}\n\t\t\taria-disabled={disabled || undefined}\n\t\t\tdata-slot=\"scratch-card\"\n\t\t\tdata-foil={foil}\n\t\t\tdata-state={revealed ? \"revealed\" : \"covered\"}\n\t\t\tdata-disabled={disabled || undefined}\n\t\t\tclassName={cn(\n\t\t\t\t\"group/scratch-card relative isolate aspect-[28/17] w-full max-w-80 select-none overflow-hidden rounded-2xl border border-black/[0.07] bg-card text-card-foreground shadow-[0_1px_2px_rgb(0_0_0/0.05),0_10px_28px_-14px_rgb(0_0_0/0.28)] dark:border-white/10 dark:shadow-[0_1px_2px_rgb(0_0_0/0.4),0_12px_32px_-14px_rgb(0_0_0/0.7)]\",\n\t\t\t\tclassName,\n\t\t\t)}\n\t\t\t{...props}\n\t\t>\n\t\t\t<motion.div\n\t\t\t\tref={contentRef}\n\t\t\t\ttabIndex={-1}\n\t\t\t\taria-hidden={!revealed}\n\t\t\t\tinert={!revealed}\n\t\t\t\tinitial={false}\n\t\t\t\tanimate={{ scale: revealed ? 1 : 0.98 }}\n\t\t\t\ttransition={revealed ? transition : { duration: 0 }}\n\t\t\t\tclassName=\"absolute inset-0 flex items-center justify-center overflow-hidden outline-none\"\n\t\t\t>\n\t\t\t\t{children}\n\t\t\t</motion.div>\n\n\t\t\t<AnimatePresence initial={false}>\n\t\t\t\t{revealed ? null : (\n\t\t\t\t\t<motion.div\n\t\t\t\t\t\tkey=\"foil\"\n\t\t\t\t\t\tref={foilRef}\n\t\t\t\t\t\ttabIndex={-1}\n\t\t\t\t\t\taria-hidden\n\t\t\t\t\t\tinitial={false}\n\t\t\t\t\t\tanimate={{ opacity: 1, scale: 1 }}\n\t\t\t\t\t\texit={{ opacity: 0, scale: reducedMotion ? 1 : 1.04 }}\n\t\t\t\t\t\ttransition={transition}\n\t\t\t\t\t\tonPointerDown={onPointerDown}\n\t\t\t\t\t\tonPointerMove={onPointerMove}\n\t\t\t\t\t\tonPointerUp={onPointerEnd}\n\t\t\t\t\t\tonPointerCancel={onPointerEnd}\n\t\t\t\t\t\tonLostPointerCapture={onPointerEnd}\n\t\t\t\t\t\tonPointerLeave={onPointerLeave}\n\t\t\t\t\t\tonKeyDown={onKeyDown}\n\t\t\t\t\t\tclassName=\"absolute inset-0 cursor-crosshair touch-none outline-none group-data-disabled/scratch-card:cursor-not-allowed group-data-disabled/scratch-card:opacity-60\"\n\t\t\t\t\t>\n\t\t\t\t\t\t{/* Shown until the canvas paints, so server HTML never shows the content. */}\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tref={fallbackRef}\n\t\t\t\t\t\t\tclassName=\"absolute inset-0 flex items-center justify-center font-semibold text-[11px] text-black/40 uppercase tracking-[0.18em]\"\n\t\t\t\t\t\t\tstyle={{ background: cssGradient(palette) }}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{hint}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<canvas ref={canvasRef} className=\"absolute inset-0 size-full\" />\n\t\t\t\t\t</motion.div>\n\t\t\t\t)}\n\t\t\t</AnimatePresence>\n\n\t\t\t{revealed ? null : (\n\t\t\t\t<button\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\tonClick={() => reveal(true)}\n\t\t\t\t\tclassName=\"absolute right-2 bottom-2 z-10 inline-flex h-7 items-center rounded-full bg-background/85 px-3 font-medium text-foreground text-xs opacity-0 pointer-coarse:opacity-100 shadow-[0_1px_2px_rgb(0_0_0/0.12)] outline-none ring-1 ring-black/5 backdrop-blur-sm transition-opacity duration-150 ease-out focus-visible:opacity-100 focus-visible:ring-3 focus-visible:ring-ring/50 group-hover/scratch-card:opacity-100 group-data-scratching/scratch-card:invisible group-data-disabled/scratch-card:hidden motion-reduce:transition-none dark:ring-white/10\"\n\t\t\t\t>\n\t\t\t\t\tReveal\n\t\t\t\t</button>\n\t\t\t)}\n\n\t\t\t<span role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n\t\t\t\t{revealed ? \"Revealed\" : \"\"}\n\t\t\t</span>\n\t\t</div>\n\t);\n}\n",
      "type": "registry:component",
      "target": "@components/scratch-card.tsx"
    }
  ],
  "meta": {
    "createdAt": "2026-11-04",
    "image": "https://cdn.tentui.com/images/components/scratch-card",
    "video": "https://cdn.tentui.com/videos/components/scratch-card"
  },
  "docs": "https://tentui.com/components/scratch-card",
  "categories": [],
  "type": "registry:component"
}