import React, { useState, useEffect, useRef } from 'react'; import { useAchievements } from '../context/AchievementContext'; const Stopwatch = () => { const [time, setTime] = useState(0); const [laps, setLaps] = useState([]); const [isRunning, setIsRunning] = useState(false); const intervalRef = useRef(null); const { unlockAchievement } = useAchievements(); const startTimeRef = useRef(0); const timeRef = useRef(time); useEffect(() => { timeRef.current = time; }, [time]); useEffect(() => { if (isRunning) { startTimeRef.current = Date.now() - timeRef.current; intervalRef.current = setInterval(() => { setTime(Date.now() - startTimeRef.current); }, 10); } else { clearInterval(intervalRef.current); } return () => clearInterval(intervalRef.current); }, [isRunning]); const handleStart = () => { setIsRunning(true); }; const handleStop = () => { setIsRunning(false); if (time >= 10000 && time < 10010) { unlockAchievement('perfect_timing'); } }; const handleReset = () => { setIsRunning(false); setTime(0); setLaps([]); }; const handleLap = () => { setLaps((prevLaps) => [...prevLaps, time]); }; const formatTime = (timeValue) => { const milliseconds = `0${Math.floor((timeValue % 1000) / 10)}`.slice(-2); const seconds = `0${Math.floor(timeValue / 1000) % 60}`.slice(-2); const minutes = `0${Math.floor(timeValue / 60000) % 60}`.slice(-2); const hours = `0${Math.floor(timeValue / 3600000)}`.slice(-2); return `${hours}:${minutes}:${seconds}.${milliseconds}`; }; const buttonStyle = 'w-24 px-4 py-2 text-lg font-arvo rounded-md border transition-colors duration-300 ease-in-out'; const activeButtonStyle = 'bg-green-800/50 border-green-700 text-white hover:bg-green-700/50'; const inactiveButtonStyle = 'bg-gray-700/50 border-gray-600 text-gray-300 hover:bg-gray-600/50'; const stopButtonStyle = 'bg-red-800/50 border-red-700 text-white hover:bg-red-700/50'; const lapButtonStyle = 'bg-blue-800/50 border-blue-700 text-white hover:bg-blue-700/50 disabled:opacity-50 disabled:cursor-not-allowed'; return (