// Differences — find the one that doesn't belong (visual attention, focus).
// Senior-friendly: large emoji, untimed, encouraging.

const SETS = [
  { theme: 'Bunga vs satu yang berbeda', same: '🌹', odd: '🌷', count: 9 },
  { theme: 'Daun', same: '🍃', odd: '🌿', count: 9 },
  { theme: 'Kucing & satu anjing', same: '🐈', odd: '🐕', count: 9 },
  { theme: 'Buah', same: '🍎', odd: '🍏', count: 9 },
  { theme: 'Bulan & matahari', same: '🌙', odd: '☀️', count: 9 },
  { theme: 'Teh & kopi', same: '🍵', odd: '☕', count: 9 },
  { theme: 'Burung', same: '🐦', odd: '🦉', count: 9 },
  { theme: 'Bintang', same: '⭐', odd: '✨', count: 9 },
];

function makeRound(set) {
  const cells = Array.from({ length: set.count }).map(() => ({ e: set.same, odd: false }));
  const oddIdx = Math.floor(Math.random() * set.count);
  cells[oddIdx] = { e: set.odd, odd: true };
  return { cells, oddIdx };
}

function pickRounds() {
  const arr = SETS.slice();
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr.slice(0, 5).map(makeRound);
}

function DifferencesGame({ onExit, onComplete }) {
  const [rounds] = React.useState(() => pickRounds());
  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 round = rounds[idx];

  const choose = (i) => {
    if (picked !== null) return;
    setTaps(t => t + 1);
    setPicked(i);
    if (i === round.oddIdx) {
      OASound.match();
      setCorrect(c => c + 1);
      setTimeout(() => {
        if (idx + 1 >= rounds.length) {
          const total = correct + 1;
          const acc = Math.round((total / rounds.length) * 100);
          onComplete({ taps, hearts, accuracy: acc });
        } else {
          setIdx(idx + 1);
          setPicked(null);
        }
      }, 900);
    } else {
      OASound.miss();
      setHearts(h => Math.max(0, h - 1));
      setTimeout(() => setPicked(null), 1000);
    }
  };

  const progress = idx / rounds.length;

  return (
    <div style={{ minHeight: '100dvh', background: 'linear-gradient(180deg, #DDE9DF 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 !== null && picked === round.oddIdx ? 'cheer' : 'happy'} />
        <div style={{ flex: 1 }}>
          <SpeechBubble accent={OA_THEME.sageDeep}>
            <b style={{ color: OA_THEME.sageDeep }}>Pilih satu yang berbeda</b> dari yang lain.
          </SpeechBubble>
        </div>
      </div>

      <div style={{ padding: '8px 22px', flex: 1 }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(3, 1fr)',
          gap: 12,
        }}>
          {round.cells.map((c, i) => {
            const isPicked = picked === i;
            const isCorrect = picked !== null && i === round.oddIdx;
            const isWrongPick = isPicked && i !== round.oddIdx;
            const bg = isCorrect ? '#EAF1EB' : isWrongPick ? '#FCEFE9' : OA_THEME.card;
            const border = isCorrect ? OA_THEME.sage : isWrongPick ? OA_THEME.rose : OA_THEME.line;
            return (
              <button key={i} onClick={() => choose(i)} disabled={picked !== null} className="oa-no-tap" aria-label="Pilih kotak" style={{
                aspectRatio: '1/1',
                background: bg, border: `2px solid ${border}`,
                borderRadius: 20,
                fontSize: 52,
                cursor: picked !== null ? 'default' : 'pointer',
                boxShadow: `0 4px 0 ${border}`,
                transition: 'all .2s',
                animation: isCorrect ? 'oaPop .6s' : 'none',
              }}>{c.e}</button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.DifferencesGame = DifferencesGame;
