'use client'; import { useEffect, useState } from 'react'; const KEYPAD = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; /** * Digit entry with the single-player rule: every digit can be used only once. * Supports clicks and the keyboard (0-9, Backspace, Enter). */ export default function NumberPad({ digitNumber, onSubmit, disabled = false, busy = false, submitLabel = 'Enter' }) { const [digits, setDigits] = useState(() => Array(digitNumber).fill('')); const used = new Set(digits.filter((d) => d !== '')); const complete = digits.every((d) => d !== ''); const locked = disabled || busy; const append = (val) => { if (locked) return; setDigits((cur) => { const s = String(val); const idx = cur.indexOf(''); if (idx === -1 || cur.includes(s)) return cur; const next = [...cur]; next[idx] = s; return next; }); }; const remove = () => { if (locked) return; setDigits((cur) => { const next = [...cur]; for (let i = next.length - 1; i >= 0; i--) { if (next[i] !== '') { next[i] = ''; break; } } return next; }); }; const submit = async () => { if (locked || !complete) return; const ok = await onSubmit(digits.join('')); if (ok !== false) setDigits(Array(digitNumber).fill('')); }; useEffect(() => { const onKey = (e) => { if (e.target instanceof HTMLInputElement) return; if (/^[0-9]$/.test(e.key)) append(e.key); else if (e.key === 'Backspace') remove(); else if (e.key === 'Enter') submit(); }; window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey); }); return (
{/* Boxes shrink to fit the screen width, so up to 10 digits fit on a phone without scrolling */}
{digits.map((d, i) => (
{d}
))}
{KEYPAD.map((n) => { const off = used.has(String(n)) || locked; return ( ); })}
); }