"use client"; import { useState, useEffect, useRef } from "react"; import { Calculator } from "lucide-react"; import { Button } from "@/components/ui/Button"; import { MiniGameResultsScreen } from "@/components/game/MiniGameResultsScreen"; import { MiniGameHeader } from "@/components/game/MiniGameHeader"; import { soundManager } from "@/lib/sound/manager"; const GAME_DURATION = 60; export default function MathGame() { const [isPlaying, setIsPlaying] = useState(false); const [isGameOver, setIsGameOver] = useState(false); const [timeLeft, setTimeLeft] = useState(GAME_DURATION); const [score, setScore] = useState(0); const [equation, setEquation] = useState({ text: "", answer: 0 }); const [inputValue, setInputValue] = useState(""); const inputRef = useRef(null); const timerRef = useRef(null); const generateEquation = () => { const ops = ["+", "-", "*"]; const op = ops[Math.floor(Math.random() * ops.length)]; let a: number, b: number, text: string, answer: number; const maxVal = 10 + Math.floor(score / 5) * 5; if (op === "+") { a = Math.floor(Math.random() * maxVal) + 1; b = Math.floor(Math.random() * maxVal) + 1; text = `${a} + ${b}`; answer = a + b; } else if (op === "-") { a = Math.floor(Math.random() * maxVal) + 10; b = Math.floor(Math.random() * a); text = `${a} - ${b}`; answer = a - b; } else { a = Math.floor(Math.random() * 12) + 2; b = Math.floor(Math.random() * 12) + 2; text = `${a} \u00d7 ${b}`; answer = a * b; } setEquation({ text, answer }); }; const startGame = () => { setIsPlaying(true); setIsGameOver(false); setScore(0); setTimeLeft(GAME_DURATION); setInputValue(""); generateEquation(); soundManager.play("streak5"); setTimeout(() => inputRef.current?.focus(), 100); }; useEffect(() => { if (!isPlaying || timeLeft <= 0) return; timerRef.current = setTimeout(() => { if (timeLeft <= 1) { setIsPlaying(false); setIsGameOver(true); setTimeLeft(0); soundManager.play("correct"); } else { if (timeLeft <= 6) soundManager.play("tick"); setTimeLeft((prev) => prev - 1); } }, 1000); return () => { if (timerRef.current) clearTimeout(timerRef.current); }; }, [isPlaying, timeLeft]); const handleInputChange = (e: React.ChangeEvent) => { if (!isPlaying) return; const val = e.target.value; if (!/^\d*$/.test(val)) return; setInputValue(val); if (parseInt(val) === equation.answer) { soundManager.play("tick"); setScore((prev) => prev + 1); setInputValue(""); generateEquation(); } }; if (isGameOver) { return ( ); } return (
{!isPlaying ? (

Core Calibration

The hyperdrive is failing! Solve as many equations as possible in 60 seconds to stabilize the core.

) : (
{equation.text}
)}
); }