// Numbers — gentle mental math. 5 questions, untimed.
function makeNumberQuestions() {
  const qs = [];
  // Q1: simple addition (1-20)
  {
    const a = 3 + Math.floor(Math.random() * 12);
    const b = 2 + Math.floor(Math.random() * 10);
    qs.push({ q: `${a} + ${b} = ?`, ans: a + b, kind: 'tambah' });
  }
  // Q2: simple subtraction (positive)
  {
    const a = 10 + Math.floor(Math.random() * 15);
    const b = 1 + Math.floor(Math.random() * 8);
    qs.push({ q: `${a} − ${b} = ?`, ans: a - b, kind: 'kurang' });
  }
  // Q3: counting items
  {
    const items = ['🍎','🍊','🍌','🍇','🍓'];
    const it = items[Math.floor(Math.random() * items.length)];
    const n = 4 + Math.floor(Math.random() * 6);
    qs.push({ q: `Ada berapa ${it}?`, visual: it.repeat(n), ans: n, kind: 'hitung' });
  }
  // Q4: small multiplication
  {
    const a = 2 + Math.floor(Math.random() * 5);
    const b = 2 + Math.floor(Math.random() * 5);
    qs.push({ q: `${a} × ${b} = ?`, ans: a * b, kind: 'kali' });
  }
  // Q5: word problem
  {
    const harga = 2000 + Math.floor(Math.random() * 5) * 1000;
    const jumlah = 2 + Math.floor(Math.random() * 4);
    qs.push({
      q: `Beli ${jumlah} pisang, harga Rp ${harga.toLocaleString('id-ID')} per buah. Total?`,
      ans: harga * jumlah,
      kind: 'cerita',
      formatRupiah: true,
    });
  }
  return qs;
}

function makeOptions(answer, formatRupiah) {
  const opts = new Set([answer]);
  while (opts.size < 4) {
    let delta = (Math.floor(Math.random() * 5) + 1) * (Math.random() > 0.5 ? 1 : -1);
    if (formatRupiah) delta *= 1000;
    const v = answer + delta;
    if (v > 0) opts.add(v);
  }
  return Array.from(opts).sort(() => Math.random() - 0.5);
}

function NumbersGame({ onExit, onComplete }) {
  const [questions] = React.useState(() => makeNumberQuestions());
  const [idx, setIdx] = React.useState(0);
  const [hearts, setHearts] = React.useState(5);
  const [taps, setTaps] = React.useState(0);
  const [picked, setPicked] = React.useState(null);
  const [correct, setCorrect] = React.useState(0);

  const q = questions[idx];
  const options = React.useMemo(() => makeOptions(q.ans, q.formatRupiah), [idx]);

  const fmt = (v) => q.formatRupiah ? `Rp ${v.toLocaleString('id-ID')}` : v;

  const choose = (v) => {
    if (picked !== null) return;
    setTaps(t => t + 1);
    setPicked(v);
    if (v === q.ans) {
      OASound.match();
      setCorrect(c => c + 1);
      setTimeout(() => {
        if (idx + 1 >= questions.length) {
          finish(correct + 1);
        } else {
          setIdx(idx + 1);
          setPicked(null);
        }
      }, 800);
    } else {
      OASound.miss();
      setHearts(h => Math.max(0, h - 1));
      setTimeout(() => setPicked(null), 1100);
    }
  };

  const finish = (totalCorrect) => {
    const acc = Math.round((totalCorrect / questions.length) * 100);
    onComplete({ taps, hearts, accuracy: acc });
  };

  const progress = idx / questions.length;

  return (
    <div style={{ minHeight: '100dvh', background: 'linear-gradient(180deg, #E2EAF0 0%, #EDE6DC 60%)', display: 'flex', flexDirection: 'column', paddingTop: 'max(20px, env(safe-area-inset-top))' }}>
      <GameTopBar onExit={onExit} progress={progress} hearts={hearts} />

      <div style={{ padding: '0 22px 12px', display:'flex', alignItems:'flex-end', gap: 14 }}>
        <Mascot size={64} mood={picked === q.ans ? 'cheer' : picked !== null ? 'think' : 'happy'} />
        <div style={{ flex: 1 }}>
          <SpeechBubble accent={OA_THEME.skyDeep}>
            <b style={{ color: OA_THEME.skyDeep }}>Soal {idx + 1} dari {questions.length}.</b> Tidak apa salah, kita coba lagi.
          </SpeechBubble>
        </div>
      </div>

      <div style={{ padding: '8px 22px', flex: 1, display: 'flex', flexDirection: 'column' }}>
        <div style={{
          background: OA_THEME.card, border: `2px solid ${OA_THEME.line}`,
          borderRadius: 22, padding: '24px 18px', textAlign: 'center',
          boxShadow: '0 4px 0 rgba(60,82,76,0.08)',
          marginBottom: 18,
        }}>
          {q.visual && <div style={{ fontSize: 38, lineHeight: 1.2, marginBottom: 14, letterSpacing: 4 }}>{q.visual}</div>}
          <div style={{ fontFamily: 'Lora, serif', fontStyle: 'italic', fontWeight: 600, fontSize: q.kind === 'cerita' ? 22 : 36, color: OA_THEME.ink, lineHeight: 1.3 }}>
            {q.q}
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          {options.map(v => {
            const isPicked = picked === v;
            const isCorrect = picked !== null && v === q.ans;
            const isWrong = isPicked && v !== q.ans;
            const bg = isCorrect ? '#EAF1EB' : isWrong ? '#FCEFE9' : OA_THEME.card;
            const border = isCorrect ? OA_THEME.sage : isWrong ? OA_THEME.rose : OA_THEME.line;
            return (
              <button key={v} onClick={() => choose(v)} disabled={picked !== null} className="oa-no-tap" style={{
                minHeight: 78, padding: '12px 8px',
                background: bg, border: `2px solid ${border}`,
                borderRadius: 18, fontSize: 24, fontWeight: 800, color: OA_THEME.ink,
                cursor: picked !== null ? 'default' : 'pointer',
                boxShadow: `0 4px 0 ${border}`,
                transition: 'all .2s',
              }}>{fmt(v)}</button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.NumbersGame = NumbersGame;
