import { useEffect, useState} from "react";
import './App.css';
import Header from "./components/Header";
import Body from "./components/Body";
import question from "./components/Question";

function App()  {
  const [timeLeft, setTimeLeft] = useState(10*1000);
  const [timerRunning, setTimerRunning] = useState(false);
  const [questionCount, setQuestionCount] = useState(0);
  const [teamsize, setTeamSize] = useState(0);

  useEffect(() => {
    let timer;
    if (timerRunning && timeLeft > 0) {
      timer = setTimeout(() => {
        setTimeLeft(timeLeft-10);
      }, 10);}
    else if (timeLeft === 0) {
      alert("Zeit ist um !");
      setTimerRunning(false);
      setTimeLeft(10);
    }
    return () => clearTimeout(timer);

  }, [timeLeft, timerRunning]);

  function formatTime(time) {
    const seconds = Math.floor((time / 1000) % 60).toString().padStart(2, '0');
    return `${seconds} s`;
  }

  const startQuestion = () => {
    if (questionCount <= 5){
      setQuestionCount(questionCount+1)
      setTimeLeft(10*1000);
      setTimerRunning(true);
    }
    else {
      alert("Spiel vorbei !");
    }
  }

  const stopTimer = () => {
    setTimerRunning(false)
    setTimeLeft(10*1000);
  }

  return (<>
    <Header timerRunning={timerRunning} timerContent={formatTime(timeLeft)} questionCount={questionCount}/>
    <Body startQuestion={startQuestion} timerRunning={timerRunning} stopTimer={stopTimer} setQuestionCount={setQuestionCount} setTeamSize={setTeamSize} teamsize={teamsize}/>
    </>
  );
}

export default App;
