// Completa el hueco — a × ? = c   o   ? × b = c
const CompletaHueco = ({ profile, onFinish, onQuit }) => {
  const t = window.MP_I18N.t;
  const diff = window.MP_DATA.difficultyForGrade(profile.grade);
  const TOTAL = 10;
  const [idx, setIdx] = React.useState(0);
  const [score, setScore] = React.useState(0);
  const [correct, setCorrect] = React.useState(0);
  const [problem, setProblem] = React.useState(null);
  const [blank, setBlank] = React.useState('a');
  const [value, setValue] = React.useState('');
  const [status, setStatus] = React.useState(null);

  const next = () => {
    const p = window.MP_DATA.genProblem({ tables: diff.tables, max: diff.max });
    setProblem(p);
    setBlank(Math.random() < 0.5 ? 'a' : 'b');
    setValue('');
    setStatus(null);
  };

  React.useEffect(() => { next(); }, []);

  const submit = () => {
    if (!value || !problem) return;
    const expected = blank === 'a' ? problem.a : problem.b;
    const isRight = parseInt(value, 10) === expected;
    if (isRight) {
      window.MP_SOUND.correct();
      setStatus('right');
      setCorrect(x => x + 1);
      setScore(s => s + 12);
    } else {
      window.MP_SOUND.wrong();
      setStatus('wrong');
    }
    setTimeout(() => {
      const ni = idx + 1;
      if (ni >= TOTAL) {
        const fc = correct + (isRight ? 1 : 0);
        onFinish({ mode: 'blank', score: score + (isRight ? 12 : 0), correct: fc, total: TOTAL, perfect: fc === TOTAL });
      } else {
        setIdx(ni);
        next();
      }
    }, 700);
  };

  return (
    <GameShell label={t('blank')} score={score} onQuit={onQuit}>
      <div className="row" style={{ justifyContent: 'space-between' }}>
        <span className="chip">{idx + 1}/{TOTAL}</span>
      </div>
      <div className="progress-bar"><div style={{ width: (idx / TOTAL * 100) + '%' }} /></div>
      {problem && (
        <div className={'problem ' + (status === 'wrong' ? 'shake' : status === 'right' ? 'pop' : '')}>
          {blank === 'a' ? <span className="blank">{value || '?'}</span> : <span>{problem.a}</span>}
          <span className="op">×</span>
          {blank === 'b' ? <span className="blank">{value || '?'}</span> : <span>{problem.b}</span>}
          <span className="eq">=</span>
          <span>{problem.answer}</span>
        </div>
      )}
      <Numpad value={value} onChange={setValue} onSubmit={submit} />
    </GameShell>
  );
};
window.CompletaHueco = CompletaHueco;
