// Verdadero o falso — fast reflex
const VerdaderoFalso = ({ profile, onFinish, onQuit }) => {
  const t = window.MP_I18N.t;
  const diff = window.MP_DATA.difficultyForGrade(profile.grade);
  const TOTAL = 60;
  const [phase, setPhase] = React.useState('count');
  const [timeLeft, setTimeLeft] = React.useState(TOTAL);
  const [score, setScore] = React.useState(0);
  const [correct, setCorrect] = React.useState(0);
  const [total, setTotal] = React.useState(0);
  const [problem, setProblem] = React.useState(null);
  const [shown, setShown] = React.useState(0);
  const [isTrue, setIsTrue] = React.useState(true);
  const [status, setStatus] = React.useState(null);

  const next = () => {
    const p = window.MP_DATA.genProblem({ tables: diff.tables, max: diff.max });
    const showTrue = Math.random() < 0.5;
    const fake = p.answer + (Math.random() < 0.5 ? -1 : 1) * (1 + Math.floor(Math.random() * 5));
    setProblem(p);
    setIsTrue(showTrue);
    setShown(showTrue ? p.answer : Math.max(1, fake));
    setStatus(null);
  };

  React.useEffect(() => {
    if (phase !== 'play') return;
    next();
    const start = Date.now();
    const id = setInterval(() => {
      const elapsed = (Date.now() - start) / 1000;
      const left = Math.max(0, TOTAL - elapsed);
      setTimeLeft(left);
      if (left <= 0) {
        clearInterval(id);
        onFinish({ mode: 'tf', score, correct, total, perfect: total > 0 && correct === total });
      }
    }, 100);
    return () => clearInterval(id);
  }, [phase]);

  const answer = (sayTrue) => {
    setTotal(x => x + 1);
    const right = sayTrue === isTrue;
    if (right) {
      window.MP_SOUND.correct();
      setStatus('right');
      setCorrect(x => x + 1);
      setScore(s => s + 8);
    } else {
      window.MP_SOUND.wrong();
      setStatus('wrong');
    }
    setTimeout(next, 280);
  };

  if (phase === 'count') {
    return (
      <GameShell label={t('tf')} score={0} timeLeft={TOTAL} totalTime={TOTAL} onQuit={onQuit}>
        <Countdown onDone={() => setPhase('play')} />
      </GameShell>
    );
  }

  return (
    <GameShell label={t('tf')} score={score} timeLeft={timeLeft} totalTime={TOTAL} onQuit={onQuit}>
      <div className={'problem ' + (status === 'wrong' ? 'shake' : status === 'right' ? 'pop' : '')}>
        <span>{problem?.a}</span><span className="op">×</span><span>{problem?.b}</span><span className="eq">=</span><span>{shown}</span>
      </div>
      <div className="tf-row">
        <button className="tf-btn tf-yes" onClick={() => answer(true)}>✓ {t('true_lbl')}</button>
        <button className="tf-btn tf-no" onClick={() => answer(false)}>✗ {t('false_lbl')}</button>
      </div>
      <div className="caption text-center">{correct}/{total}</div>
    </GameShell>
  );
};
window.VerdaderoFalso = VerdaderoFalso;
