import React, { useState, useEffect, useRef } from "react" import { dotPositions } from "./diceDotPositions" const Dice = ({ onRoll, selectedValue }) => { const [diceValue, setDiceValue] = useState(1) const [isRolling, setIsRolling] = useState(false) const animationRef = useRef(null) const rollTimeoutRef = useRef(null) const diceFaces = [ [
], [ , , ], [ , , , ], [ , , , , ], [ , , , , , ], [ , , , , , , ], ] useEffect(() => { return () => { if (animationRef.current) cancelAnimationFrame(animationRef.current) if (rollTimeoutRef.current) clearTimeout(rollTimeoutRef.current) } }, []) // Helper that starts the rolling animation and finishes with targetValue if provided const startRoll = (targetValue = null) => { if (isRolling) return setIsRolling(true) let duration = 0 const rollInterval = 80 // ms between dice face changes const maxDuration = 1500 // total animation time const rollAnimation = () => { const randomValue = Math.floor(Math.random() * 6) + 1 setDiceValue(randomValue) duration += rollInterval if (duration < maxDuration) { // Speed effect: slow down towards the end const nextInterval = rollInterval * (1 + (duration / maxDuration) * 2) rollTimeoutRef.current = setTimeout(() => { animationRef.current = requestAnimationFrame(rollAnimation) }, nextInterval) } else { // Final roll (use targetValue if provided) const finalValue = targetValue != null ? Number(targetValue) : Math.floor(Math.random() * 6) + 1 setDiceValue(finalValue) setIsRolling(false) if (onRoll) onRoll(finalValue) } } animationRef.current = requestAnimationFrame(rollAnimation) } // Click to roll randomly const rollDice = () => { startRoll(null) } // If parent provides a selectedValue, animate to that value useEffect(() => { if (selectedValue != null) { startRoll(Number(selectedValue)) } }, [selectedValue]) return (