"use client";import * as React from "react";import { INTERACTION_FOCUS, INTERACTION_PRESS, createSpring, useInteractionActivity, useInteractionReducedMotion, type Spring,} from "./ui-interaction-motion";import { playSound } from "./ui-sounds";/* ───────────────────────────────────────────────────────── * AMOUNT FIELD: hero auto-scale money & credits composer * * scale the figure is the hero: as digits arrive, a spring * measures real text width and scales typography down * smoothly (56px -> 24px) so large amounts never wrap * or clip, then breathes back up as you delete * * motion thousands separators open smoothly between digits * by place-value key; the hairline caret glides on a * spring with subtle velocity stretch and blinks only * at rest; clicking Max or a preset smoothly rolls the * figure from its current value * * balance crossing `balance` triggers a damped recoil + rose * 8×8 Bayer floor pulse, tints the figure crimson and * names the exact shortfall with a one-tap Set to max * ───────────────────────────────────────────────────────── */export interface AmountConversion { /** Multiplier applied to the entered numeric amount (e.g. 0.9214 for USD -> EUR, or 1000 for $ -> credits). */ rate: number; /** Target ISO 4217 currency code (e.g. "EUR", "GBP"). */ currency?: string; /** Target non-currency unit label (e.g. "credits", "ETH", "pts"). */ unit?: string; /** Fraction digits for the converted output (defaults to 2 for currency, 0 for unit). */ decimals?: number; /** Optional rate note displayed beside the output (e.g. "1 USD = 0.9214 EUR"). */ rateLabel?: string;}export interface AmountFieldProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "defaultValue" | "onChange"> { /** Controlled numeric value, or null when empty. */ value?: number | null; /** Initial uncontrolled value (default null). */ defaultValue?: number | null; /** Called with the parsed number or null whenever the value changes. */ onChange?: (value: number | null) => void; /** ISO 4217 currency code (default "USD"). */ currency?: string; /** Explicit symbol or token label overriding Intl's currency symbol (e.g. "USDC"). */ symbol?: string; /** Where the symbol renders relative to the figure (default "prefix"). */ symbolPosition?: "prefix" | "suffix"; /** BCP 47 locale for grouping and decimal marks (default "en-US"). */ locale?: string; /** Max fractional digits allowed (defaults to currency's standard fraction digits). */ decimals?: number; /** Available balance or spending cap: enables Max roll-up and overdraft shortfall readout. */ balance?: number; /** Optional quick-pick preset amounts (e.g. [50, 250, 1000]). */ presets?: number[]; /** Optional live FX or credits conversion readout underneath the figure. */ conversion?: AmountConversion; /** Accessible name for the numeric input (default "Amount"). */ label?: string; /** Disabled state. */ disabled?: boolean; /** Opt-in quiet Web Audio ticks on typing, preset roll and overdraft (from ui-sounds.ts). */ sound?: boolean;}interface GlyphToken { key: string; ch: string; kind: "digit" | "sep" | "dot" | "frac"; /** Character index inside raw `draft` immediately AFTER this glyph. */ rawAfter: number;}const BAYER8: Float32Array = (() => { const m = [ [0, 32, 8, 40, 2, 34, 10, 42], [48, 16, 56, 24, 50, 18, 58, 26], [12, 44, 4, 36, 14, 46, 6, 38], [60, 28, 52, 20, 62, 30, 54, 22], [3, 35, 11, 43, 1, 33, 9, 41], [51, 19, 59, 27, 49, 17, 57, 25], [15, 47, 7, 39, 13, 45, 5, 37], [63, 31, 55, 23, 61, 29, 53, 21], ]; const out = new Float32Array(64); for (let y = 0; y < 8; y++) { for (let x = 0; x < 8; x++) { out[(y << 3) | x] = (m[y][x] + 0.5) / 64; } } return out;})();const IS_LE = (() => { const b = new ArrayBuffer(4); new Uint32Array(b)[0] = 0x0a0b0c0d; return new Uint8Array(b)[0] === 0x0d;})();function packRgba(r: number, g: number, b: number, a: number): number { const ri = r < 0 ? 0 : r > 255 ? 255 : r | 0; const gi = g < 0 ? 0 : g > 255 ? 255 : g | 0; const bi = b < 0 ? 0 : b > 255 ? 255 : b | 0; const ai = a < 0 ? 0 : a > 255 ? 255 : a | 0; return IS_LE ? ((ai << 24) | (bi << 16) | (gi << 8) | ri) >>> 0 : ((ri << 24) | (gi << 16) | (bi << 8) | ai) >>> 0;}const clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v);const clamp01 = (v: number) => (Number.isFinite(v) ? clamp(v, 0, 1) : 0);function getLocaleMeta(locale: string, currency: string) { let group = ","; let decimal = "."; let curSymbol = "$"; let defaultDecimals = 2; try { const nf = new Intl.NumberFormat(locale, { style: "currency", currency }); const opts = nf.resolvedOptions(); defaultDecimals = opts.maximumFractionDigits ?? 2; const parts = nf.formatToParts(12345.67); for (const p of parts) { if (p.type === "group") group = p.value; else if (p.type === "decimal") decimal = p.value; else if (p.type === "currency") curSymbol = p.value; } } catch { // Fallback to USD/en-US defaults } return { group, decimal, curSymbol, defaultDecimals };}function numberToDraft(n: number | null | undefined, maxDecimals: number): string { if (n === null || n === undefined || !Number.isFinite(n)) return ""; const abs = Math.max(0, n); if (maxDecimals <= 0) return String(Math.round(abs)); const fixed = abs.toFixed(maxDecimals); // Trim unnecessary trailing zeroes while preserving clean decimals return fixed.replace(/\.?0+$/, "") || "0";}function sanitizeDraft(raw: string, maxDecimals: number, localeDecimal: string): string { let s = raw.replace(/\s+/g, ""); // Normalize pasted European decimal comma when unambiguous if (localeDecimal === ",") { s = s.replace(/\./g, "").replace(/,/g, "."); } else { s = s.replace(/,/g, ""); } let out = ""; let seenDot = false; let intCount = 0; let fracCount = 0; for (let i = 0; i < s.length; i++) { const ch = s[i]; if (ch >= "0" && ch <= "9") { if (seenDot) { if (fracCount < maxDecimals) { out += ch; fracCount++; } } else { if (intCount < 11) { out += ch; intCount++; } } } else if (ch === "." && maxDecimals > 0 && !seenDot) { if (out.length === 0) { out = "0."; intCount = 1; } else { out += "."; } seenDot = true; } } // Strip redundant leading zeros like "005" -> "5", keeping "0" and "0.xxx" if (!seenDot && out.length > 1 && out.startsWith("0")) { out = out.replace(/^0+/, "") || "0"; } else if (seenDot && out.startsWith("00")) { const [ip, fp] = out.split("."); out = `${ip.replace(/^0+/, "") || "0"}.${fp ?? ""}`; } return out;}function parseDraft(draft: string): number | null { if (!draft) return null; const n = Number(draft); return Number.isFinite(n) ? n : null;}function formatMoney(n: number, locale: string, currency: string, symbolOverride?: string, symbolPosition: "prefix" | "suffix" = "prefix", decimals?: number): string { if (symbolOverride) { const formatted = new Intl.NumberFormat(locale, { minimumFractionDigits: decimals ?? 0, maximumFractionDigits: decimals ?? 2, }).format(n); return symbolPosition === "suffix" ? `${formatted} ${symbolOverride}` : `${symbolOverride}${formatted}`; } try { return new Intl.NumberFormat(locale, { style: "currency", currency, ...(decimals !== undefined ? { minimumFractionDigits: decimals, maximumFractionDigits: decimals } : {}), }).format(n); } catch { return `$${n.toLocaleString(locale)}`; }}function buildTokens(draft: string, groupSep: string, decimalSep: string): GlyphToken[] { if (!draft) return []; const dotIdx = draft.indexOf("."); const intPart = dotIdx === -1 ? draft : draft.slice(0, dotIdx); const fracPart = dotIdx === -1 ? "" : draft.slice(dotIdx + 1); const tokens: GlyphToken[] = []; const len = intPart.length; for (let i = 0; i < len; i++) { const placeFromRight = len - 1 - i; tokens.push({ key: `int-${placeFromRight}`, ch: intPart[i], kind: "digit", rawAfter: i + 1, }); if (placeFromRight > 0 && placeFromRight % 3 === 0) { tokens.push({ key: `sep-${placeFromRight / 3}`, ch: groupSep, kind: "sep", rawAfter: i + 1, }); } } if (dotIdx !== -1) { tokens.push({ key: "dot", ch: decimalSep, kind: "dot", rawAfter: dotIdx + 1, }); for (let j = 0; j < fracPart.length; j++) { tokens.push({ key: `frac-${j}`, ch: fracPart[j], kind: "frac", rawAfter: dotIdx + 2 + j, }); } } return tokens;}export function AmountField({ value: controlledValue, defaultValue = null, onChange, currency = "USD", symbol, symbolPosition = "prefix", locale = "en-US", decimals: decimalsProp, balance, presets, conversion, label = "Amount", disabled = false, sound = false, className = "", ...props}: AmountFieldProps) { const reduced = useInteractionReducedMotion(); const { ref: rootRef, active: onScreen } = useInteractionActivity<HTMLDivElement>(); const meta = React.useMemo(() => getLocaleMeta(locale, currency), [locale, currency]); const maxDecimals = decimalsProp ?? meta.defaultDecimals; const displaySymbol = symbol ?? meta.curSymbol; const [draft, setDraft] = React.useState<string>(() => numberToDraft(controlledValue !== undefined ? controlledValue : defaultValue, maxDecimals), ); const [rollingDraft, setRollingDraft] = React.useState<string | null>(null); const [focused, setFocused] = React.useState(false); const [caretRawIdx, setCaretRawIdx] = React.useState<number>(() => draft.length); const [caretIdle, setCaretIdle] = React.useState(true); const [liveStatus, setLiveStatus] = React.useState(""); // Sync controlled value changes when they differ from current parsed draft (preserves typing "12." cleanly) const draftNum = parseDraft(draft); const effectiveNum = controlledValue !== undefined ? controlledValue : draftNum; const shownDraft = rollingDraft !== null ? rollingDraft : controlledValue !== undefined && controlledValue !== draftNum ? numberToDraft(controlledValue, maxDecimals) : draft; const isOverBalance = balance !== undefined && effectiveNum !== null && effectiveNum > balance; const shortfall = isOverBalance && balance !== undefined && effectiveNum !== null ? effectiveNum - balance : 0; const tokens = React.useMemo( () => buildTokens(shownDraft, meta.group, meta.decimal), [shownDraft, meta.group, meta.decimal], ); const stageRef = React.useRef<HTMLDivElement>(null); const scalerRef = React.useRef<HTMLDivElement>(null); const measureRef = React.useRef<HTMLSpanElement>(null); const digitsRef = React.useRef<HTMLSpanElement>(null); const caretElRef = React.useRef<HTMLSpanElement>(null); const inputRef = React.useRef<HTMLInputElement>(null); const floorCanvasRef = React.useRef<HTMLCanvasElement>(null); const scaleSpringRef = React.useRef<Spring | null>(null); const caretSpringRef = React.useRef<Spring | null>(null); const recoilSpringRef = React.useRef<Spring | null>(null); const rollRafRef = React.useRef(0); const idleTimerRef = React.useRef(0); const prevOverRef = React.useRef(false); const flashTriggerRef = React.useRef<((kind: "over" | "roll") => void) | null>(null); // Measure unscaled natural figure width vs available stage width (with generous side breathing room) -> drive fluid scaleSpring! const updateScale = React.useCallback( (jumpNow = false) => { const stage = stageRef.current; const measure = measureRef.current; const sp = scaleSpringRef.current; if (!stage || !measure || !sp) return; const avail = Math.max(120, stage.clientWidth - 64); const natural = Math.max(1, measure.offsetWidth); const target = clamp(avail / natural, 0.42, 1); if (jumpNow || reduced) sp.jump(target); else sp.set(target); }, [reduced], ); // Measure exact caret X inside `digitsRef` for current `caretRawIdx` -> drive spring-gliding caret! const updateCaretPos = React.useCallback( (rawIdx: number, jumpNow = false) => { const digitsEl = digitsRef.current; const sp = caretSpringRef.current; if (!digitsEl || !sp) return; let targetX = 0; if (shownDraft.length > 0) { const clamped = clamp(rawIdx, 0, shownDraft.length); const children = digitsEl.children; // Find last glyph whose rawAfter <= clamped let lastMatch = -1; for (let i = 0; i < tokens.length; i++) { if (tokens[i].rawAfter <= clamped) lastMatch = i; } if (lastMatch >= 0 && children[lastMatch]) { const el = children[lastMatch] as HTMLElement; targetX = el.offsetLeft + el.offsetWidth; } else if (children[0]) { targetX = (children[0] as HTMLElement).offsetLeft; } } if (jumpNow || reduced) sp.jump(targetX); else sp.set(targetX); }, [shownDraft.length, tokens, reduced], ); const bumpCaretActive = React.useCallback(() => { setCaretIdle(false); window.clearTimeout(idleTimerRef.current); idleTimerRef.current = window.setTimeout(() => setCaretIdle(true), 420); }, []); React.useEffect(() => () => window.clearTimeout(idleTimerRef.current), []); // Core springs: fluid optical auto-scale, gliding velocity-stretch caret, overdraft recoil React.useEffect(() => { const scaleSp = createSpring( 1, { stiffness: 250, damping: 25 }, () => { if (!scalerRef.current) return; const s = scaleSp.get(); const rx = recoilSpringRef.current?.get() ?? 0; scalerRef.current.style.transform = `translate3d(${rx.toFixed(2)}px, 0, 0) scale(${s.toFixed(4)})`; }, 0.001, ); const recoilSp = createSpring( 0, { stiffness: 450, damping: 17 }, () => { if (!scalerRef.current) return; const s = scaleSp.get(); const rx = recoilSp.get(); scalerRef.current.style.transform = `translate3d(${rx.toFixed(2)}px, 0, 0) scale(${s.toFixed(4)})`; }, 0.04, ); const caretSp = createSpring( 0, { stiffness: 360, damping: 28 }, () => { const el = caretElRef.current; if (!el) return; const x = caretSp.get(); const vel = Math.abs(caretSp.getVelocity()); // Subtle velocity stretch as the hairline caret glides between digits const stretch = clamp(1 + vel / 900, 1, 1.85); el.style.transform = `translate3d(${x.toFixed(2)}px, 0, 0) scaleX(${stretch.toFixed(3)})`; }, 0.1, ); scaleSpringRef.current = scaleSp; recoilSpringRef.current = recoilSp; caretSpringRef.current = caretSp; const ro = new ResizeObserver(() => updateScale(true)); if (stageRef.current) ro.observe(stageRef.current); return () => { ro.disconnect(); scaleSp.stop(); recoilSp.stop(); caretSp.stop(); cancelAnimationFrame(rollRafRef.current); scaleSpringRef.current = null; recoilSpringRef.current = null; caretSpringRef.current = null; }; }, [updateScale]); // Re-evaluate scale & caret position whenever displayed tokens change React.useLayoutEffect(() => { updateScale(false); updateCaretPos(caretRawIdx, false); }, [shownDraft, tokens, caretRawIdx, updateScale, updateCaretPos]); // Optical 8×8 Bayer edge floor pulse (runs strictly during a 0.48s overdraft or Max roll flash -> 0% CPU at rest!) React.useEffect(() => { const canvas = floorCanvasRef.current; const ctx = canvas?.getContext("2d"); if (!canvas || !ctx) return; const gridCanvas = document.createElement("canvas"); const gridCtx = gridCanvas.getContext("2d"); if (!gridCtx) return; let raf = 0; let flashKind: "none" | "over" | "roll" = "none"; let age = 0; let last = 0; let gCols = 0; let gRows = 0; let gridImg: ImageData | null = null; let gridU32: Uint32Array | null = null; const tick = (now: number) => { const dt = last ? Math.min(1 / 24, (now - last) / 1000) : 1 / 60; last = now; age += dt; const life = flashKind === "over" ? 0.5 : 0.48; if (age >= life || !onScreen || reduced) { flashKind = "none"; raf = 0; ctx.clearRect(0, 0, canvas.width, canvas.height); return; } const rect = canvas.getBoundingClientRect(); const w = Math.round(rect.width); const h = Math.round(rect.height); if (w > 0 && h > 0) { const dpr = Math.min(2, window.devicePixelRatio || 1); if (canvas.width !== Math.round(w * dpr) || canvas.height !== Math.round(h * dpr)) { canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr); } const pitch = 1.5; const cols = Math.max(1, Math.ceil(w / pitch)); const rows = Math.max(1, Math.ceil(h / pitch)); if (cols !== gCols || rows !== gRows || !gridImg || !gridU32) { gCols = cols; gRows = rows; gridCanvas.width = cols; gridCanvas.height = rows; gridImg = gridCtx.createImageData(cols, rows); gridU32 = new Uint32Array(gridImg.data.buffer); } const u32 = gridU32; u32.fill(0); const k = age / life; const fade = Math.sin(Math.PI * Math.pow(k, 0.72)); const front = (1 - Math.pow(1 - k, 2.2)) * 1.16 - 0.06; const rgb: [number, number, number] = flashKind === "over" ? [239, 68, 68] : [52, 211, 153]; for (let r = 0; r < rows; r++) { const v = (r + 0.5) / rows; const floorV = Math.pow(v, 1.8); const bRow = (r & 7) << 3; const rowOff = r * cols; for (let c = 0; c < cols; c++) { const u = (c + 0.5) / cols; let boost = 0; if (flashKind === "over") { boost = floorV * (0.45 + 0.55 * Math.pow(1 - Math.abs(u - 0.5) * 2, 0.6)) * fade; } else { const df = u - front; const lead = Math.exp(-(df * df) / 0.022); const tail = df < 0 ? Math.exp(df / 0.24) * 0.45 : 0; boost = floorV * (lead + tail) * fade; } const bayer = BAYER8[bRow | (c & 7)]; const hit = clamp01((boost * 0.85 - bayer + 0.05) / 0.14); if (hit > 0.02) { u32[rowOff + c] = packRgba(rgb[0], rgb[1], rgb[2], hit * 0.68 * 255); } } } gridCtx.putImageData(gridImg, 0, 0); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, w, h); ctx.imageSmoothingEnabled = false; ctx.drawImage(gridCanvas, 0, 0, cols * pitch, rows * pitch); } raf = requestAnimationFrame(tick); }; flashTriggerRef.current = (kind) => { if (reduced || !onScreen) return; flashKind = kind; age = 0; last = 0; if (!raf) raf = requestAnimationFrame(tick); }; return () => { flashTriggerRef.current = null; cancelAnimationFrame(raf); }; }, [onScreen, reduced]); // Fire overdraft recoil + Bayer floor pulse strictly on crossing into overdraft (never spamming every keystroke) React.useEffect(() => { if (isOverBalance && !prevOverRef.current) { if (!reduced) recoilSpringRef.current?.push(165); flashTriggerRef.current?.("over"); if (sound) playSound("error", 0.34); } prevOverRef.current = isOverBalance; }, [isOverBalance, reduced, sound]); const commitDraft = React.useCallback( (nextDraft: string, nextCaret?: number) => { cancelAnimationFrame(rollRafRef.current); setRollingDraft(null); setDraft(nextDraft); const parsed = parseDraft(nextDraft); onChange?.(parsed); setCaretRawIdx(nextCaret ?? nextDraft.length); bumpCaretActive(); }, [onChange, bumpCaretActive], ); // Smooth bounded ease-out roll-up / roll-down for Max and quick preset pills (commits cleanly in 260ms at any scale!) const rollToAmount = React.useCallback( (targetAmount: number, announceLabel?: string) => { if (disabled) return; const start = effectiveNum ?? 0; const cleanTarget = Math.max(0, Number(targetAmount.toFixed(maxDecimals))); const finalStr = numberToDraft(cleanTarget, maxDecimals); cancelAnimationFrame(rollRafRef.current); setDraft(finalStr); onChange?.(cleanTarget); setCaretRawIdx(finalStr.length); if (announceLabel) setLiveStatus(announceLabel); if (reduced || Math.abs(cleanTarget - start) < 1e-6) { setRollingDraft(null); if (sound) playSound("pop", 0.32); return; } flashTriggerRef.current?.("roll"); if (sound) playSound("pop", 0.32); const duration = 260; const t0 = performance.now(); let lastPaint = 0; const step = (now: number) => { const k = clamp01((now - t0) / duration); if (k >= 1) { setRollingDraft(null); rollRafRef.current = 0; return; } // Throttle visual roll updates to ~30fps (~8 smooth steps) so 4x CPU stays locked at 60fps if (now - lastPaint >= 28) { lastPaint = now; const eased = 1 - Math.pow(1 - k, 3); const cur = start + (cleanTarget - start) * eased; const rounded = maxDecimals > 0 && Math.abs(cleanTarget - start) < 100 ? Number(cur.toFixed(maxDecimals)) : Math.round(cur); setRollingDraft(numberToDraft(Math.max(0, rounded), maxDecimals)); } rollRafRef.current = requestAnimationFrame(step); }; rollRafRef.current = requestAnimationFrame(step); }, [disabled, effectiveNum, maxDecimals, reduced, sound, onChange], ); const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => { const raw = e.target.value; const sel = e.target.selectionStart ?? raw.length; const clean = sanitizeDraft(raw, maxDecimals, meta.decimal); const delta = raw.length - clean.length; const nextSel = clamp(sel - delta, 0, clean.length); commitDraft(clean, nextSel); if (sound && clean.length > shownDraft.length) playSound("tick", 0.24); }; const syncSelectionFromInput = () => { const el = inputRef.current; if (!el) return; setCaretRawIdx(clamp(el.selectionStart ?? shownDraft.length, 0, shownDraft.length)); bumpCaretActive(); }; // Click anywhere on the hero figure to place the caret at the nearest character boundary const handleStagePointerDown = (e: React.PointerEvent<HTMLDivElement>) => { if (disabled) return; if ((e.target as HTMLElement).closest("button")) return; e.preventDefault(); const input = inputRef.current; if (!input) return; input.focus(); const digitsEl = digitsRef.current; if (digitsEl && tokens.length > 0) { let bestRaw = shownDraft.length; let bestDist = Infinity; const children = digitsEl.children; // Check position before first glyph if (children[0]) { const r0 = (children[0] as HTMLElement).getBoundingClientRect(); bestDist = Math.abs(e.clientX - r0.left); bestRaw = 0; } for (let i = 0; i < tokens.length; i++) { const el = children[i] as HTMLElement | undefined; if (!el) continue; const r = el.getBoundingClientRect(); const dist = Math.abs(e.clientX - r.right); if (dist < bestDist) { bestDist = dist; bestRaw = tokens[i].rawAfter; } } input.setSelectionRange(bestRaw, bestRaw); setCaretRawIdx(bestRaw); bumpCaretActive(); } else { input.setSelectionRange(shownDraft.length, shownDraft.length); setCaretRawIdx(shownDraft.length); bumpCaretActive(); } }; // Live conversion output const convertedText = React.useMemo(() => { if (!conversion) return null; const base = effectiveNum ?? 0; const out = base * conversion.rate; const dec = conversion.decimals ?? (conversion.currency ? 2 : 0); if (conversion.currency) { return formatMoney(out, locale, conversion.currency, undefined, "prefix", dec); } const numStr = new Intl.NumberFormat(locale, { minimumFractionDigits: dec, maximumFractionDigits: dec, }).format(out); return conversion.unit ? `${numStr} ${conversion.unit}` : numStr; }, [conversion, effectiveNum, locale]); const showFooterRow = balance !== undefined || Boolean(conversion); const showPresetsRow = Boolean(presets && presets.length > 0); return ( <div ref={rootRef} className={`flex w-full flex-col gap-2.5 ${className}`} {...props}> {/* Hairline hero composer card */} <div data-focused={focused ? "true" : "false"} data-over-balance={isOverBalance ? "true" : "false"} className={`relative overflow-hidden rounded-[18px] border bg-card text-card-foreground transition-[border-color,box-shadow] duration-200 shadow-[inset_0_0.5px_0_rgb(255_255_255/0.75)] dark:shadow-[inset_0_0.5px_0_rgb(255_255_255/0.06)] ${ isOverBalance ? "border-red-500/45 dark:border-red-400/45" : focused ? "border-foreground/25" : "border-border hover:border-foreground/20" } ${disabled ? "opacity-55" : ""}`} > {/* Subtle 8×8 Bayer optical floor pulse on overdraft or Max roll (0% CPU at rest) */} <canvas ref={floorCanvasRef} aria-hidden="true" className="pointer-events-none absolute inset-x-1 bottom-1 z-0 h-8 w-[calc(100%_-_8px)] rounded-b-[13px]" /> {/* Hero auto-scaling interactive figure stage */} <div ref={stageRef} onPointerDown={handleStagePointerDown} className={`relative z-10 flex h-[108px] w-full items-center justify-center px-4 ${ disabled ? "cursor-not-allowed" : "cursor-text" }`} > {/* Native decimal input: owns real keyboard, paste, selection, undo & mobile numeric keypad */} <input ref={inputRef} type="text" inputMode={maxDecimals > 0 ? "decimal" : "numeric"} autoComplete="off" spellCheck={false} disabled={disabled} aria-label={label} aria-invalid={isOverBalance || undefined} value={shownDraft} onChange={handleInputChange} onSelect={syncSelectionFromInput} onKeyUp={syncSelectionFromInput} onFocus={() => { setFocused(true); syncSelectionFromInput(); }} onBlur={() => setFocused(false)} className="sr-only" /> {/* Spring-scaled hero typography */} <div ref={scalerRef} className="origin-center will-change-transform"> <span ref={measureRef} aria-hidden="true" className={`inline-flex items-baseline whitespace-nowrap font-sans text-[54px] font-medium leading-none tracking-[-0.04em] tabular-nums transition-colors duration-200 ${ isOverBalance ? "text-red-600 dark:text-red-400" : "text-foreground" }`} > {symbolPosition === "prefix" && ( <span className={`mr-1 text-[0.62em] font-normal tracking-normal transition-colors duration-200 ${ isOverBalance ? "text-red-500/80 dark:text-red-400/80" : shownDraft ? "text-muted-foreground" : "text-muted-foreground/45" }`} > {displaySymbol} </span> )} {/* Digit tokens + smooth spring-gliding hairline caret */} <span className="relative inline-flex items-baseline"> <span ref={digitsRef} className="inline-flex items-baseline"> {tokens.length === 0 ? ( <span className="text-muted-foreground/35">0</span> ) : ( tokens.map((tok) => ( <span key={tok.key} className={ tok.kind === "sep" ? `inline-block ${isOverBalance ? "text-red-500/70 dark:text-red-400/70" : "text-muted-foreground/65"}` : tok.kind === "dot" || tok.kind === "frac" ? `inline-block ${isOverBalance ? "text-red-500/85 dark:text-red-400/85" : "text-foreground/75"}` : "inline-block" } > {tok.ch} </span> )) )} </span> {/* Spring-gliding hairline caret (blinks only at rest!) */} <span ref={caretElRef} aria-hidden="true" className={`pointer-events-none absolute left-0 top-[0.06em] h-[0.92em] w-[2px] origin-left rounded-full transition-opacity duration-150 ${ isOverBalance ? "bg-red-500" : "bg-primary" } ${focused ? (caretIdle && !reduced ? "animate-pulse opacity-100" : "opacity-100") : "opacity-0"}`} /> </span> {symbolPosition === "suffix" && ( <span className={`ml-2 text-[0.42em] font-medium tracking-normal uppercase transition-colors duration-200 ${ isOverBalance ? "text-red-500/80 dark:text-red-400/80" : "text-muted-foreground" }`} > {displaySymbol} </span> )} </span> </div> </div> {/* Hairline balance / overdraft / conversion footer */} {showFooterRow && ( <div className="relative z-10 flex flex-wrap items-center justify-between gap-2 border-t border-border/80 bg-muted/20 px-3.5 py-2.5 text-[12px]"> {balance !== undefined ? ( isOverBalance ? ( <div className="flex w-full items-center justify-between gap-2"> <span role="alert" className="font-medium tabular-nums text-red-600 dark:text-red-400"> {formatMoney(shortfall, locale, currency, symbol, symbolPosition, maxDecimals)} over balance </span> <button type="button" disabled={disabled} onClick={() => rollToAmount(balance, `Set to maximum ${balance}`)} className={`inline-flex h-6 cursor-pointer items-center rounded-[7px] border border-red-500/30 bg-background px-2 text-[11.5px] font-medium text-foreground hover:bg-accent ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > Set to max </button> </div> ) : ( <div className="flex items-center gap-2 text-muted-foreground"> <span className="tabular-nums"> Available {formatMoney(balance, locale, currency, symbol, symbolPosition, maxDecimals)} </span> <button type="button" disabled={disabled || effectiveNum === balance} onClick={() => rollToAmount(balance, `Set to maximum ${balance}`)} className={`inline-flex h-5 cursor-pointer items-center rounded-[6px] border border-border bg-background px-1.5 text-[11px] font-medium text-foreground hover:bg-accent disabled:cursor-default disabled:opacity-40 ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > Max </button> </div> ) ) : ( <span /> )} {conversion && !isOverBalance && ( <div className="ml-auto flex items-center gap-1.5 text-right tabular-nums"> <span className="font-medium text-foreground">≈ {convertedText}</span> {conversion.rateLabel && <span className="hidden text-muted-foreground sm:inline">· {conversion.rateLabel}</span>} </div> )} </div> )} </div> {/* Optional quick-pick preset hairline pills */} {showPresetsRow && ( <div className="flex flex-wrap items-center justify-center gap-1.5"> {presets!.map((amt) => { const active = effectiveNum === amt; return ( <button key={amt} type="button" disabled={disabled} onClick={() => rollToAmount(amt, `Amount set to ${amt}`)} className={`inline-flex h-8 cursor-pointer items-center rounded-full border px-3 text-[12.5px] font-medium tabular-nums transition-colors duration-150 ${ active ? "border-foreground/25 bg-accent text-foreground" : "border-border bg-card text-muted-foreground hover:bg-accent hover:text-foreground" } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > {formatMoney(amt, locale, currency, symbol, symbolPosition, 0)} </button> ); })} </div> )} <span className="sr-only" role="status" aria-live="polite"> {liveStatus} </span> </div> );}export default AmountField;