// Activities 6–8: quiz, bucket list builder, certificate
const { useState, useEffect, useRef, useMemo } = React;

// ---------- 6. Big Sunshine Quiz ----------
const QUIZ = [
  { q: 'It is cold and sweet. You eat it in summer.', options: ['a kite', 'ice cream', 'a bike'], answer: 'ice cream' },
  { q: 'You build this with sand.', options: ['a sandcastle', 'a picnic', 'a watermelon'], answer: 'a sandcastle' },
  { q: 'You do this in the sea.', options: ['ride', 'fly', 'swim'], answer: 'swim' },
  { q: 'It flies in the sky on a windy day.', options: ['a kite', 'a sandcastle', 'an ice cream'], answer: 'a kite' },
  { q: 'It is a big fruit. It is green and red.', options: ['a bike', 'a watermelon', 'a beach'], answer: 'a watermelon' },
  { q: 'Where do you build a sandcastle?', options: ['at school', 'at the beach', 'in bed'], answer: 'at the beach' },
];

function QuizActivity({ onComplete, earn }) {
  const [idx, setIdx] = useState(0);
  const [score, setScore] = useState(0);
  const [picked, setPicked] = useState(null); // word picked this question
  const q = QUIZ[idx] || null;
  const finished = idx >= QUIZ.length;
  const awardedRef = useRef(false);

  useEffect(() => {
    if (finished && !awardedRef.current) {
      awardedRef.current = true;
      earn(score);
      if (score >= 4) { SFX.win(); burstConfetti(40); } else { SFX.star(); }
    }
  }, [finished]);

  function pick(word, e) {
    if (picked !== null) return;
    setPicked(word);
    const right = word === q.answer;
    if (right) { SFX.correct(); starPop(e.clientX, e.clientY); setScore(score + 1); }
    else SFX.wrong();
    setTimeout(() => { setPicked(null); setIdx(idx + 1); }, 1100);
  }

  return (
    <ActivityShell stepNo="6" title="The Big Sunshine Quiz"
      instructions="Read (or listen) and tap the right answer!">
      {!finished ? (
        <div className="quiz-wrap">
          <div className="quiz-progress">
            {QUIZ.map((_, i) => (
              <div key={i} className={'quiz-dot' + (i < idx ? ' quiz-dot-done' : '') + (i === idx ? ' quiz-dot-now' : '')}></div>
            ))}
          </div>
          <div className="quiz-card">
            <p className="quiz-q">{q.q}</p>
            <ListenBtn text={q.q} />
            <div className="quiz-options">
              {q.options.map((w) => {
                let cls = 'btn quiz-opt';
                if (picked !== null) {
                  if (w === q.answer) cls += ' quiz-opt-right';
                  else if (w === picked) cls += ' quiz-opt-wrong';
                  else cls += ' quiz-opt-dim';
                }
                return (
                  <button key={w} type="button" className={cls} disabled={picked !== null}
                    onClick={(e) => pick(w, e)}>
                    {w}
                  </button>
                );
              })}
            </div>
          </div>
          <div className="foot-hint quiz-score">Score: {score} ★</div>
        </div>
      ) : (
        <div className="mini-done">
          <div className="mini-done-big">{score} / {QUIZ.length} ★</div>
          <p>{score >= 5 ? 'WOW! Quiz champion!' : score >= 3 ? 'Great job!' : 'Good try! You can play again.'}</p>
          {score < QUIZ.length && (
            <button type="button" className="btn btn-ghost" onClick={() => {
              SFX.click(); setIdx(0); setScore(0); awardedRef.current = true;
            }}>Try again</button>
          )}
        </div>
      )}
      <div className="activity-foot">
        <span></span>
        <NextBtn onClick={onComplete} disabled={!finished} label="My Bucket List" />
      </div>
    </ActivityShell>
  );
}

// ---------- 7. My Bucket List + Certificate ----------
const BUCKET_KEY = 'sbl-bucket-v1';
function BucketActivity({ name, stars, earn, buddy }) {
  const [state, setState] = useState(() => {
    try {
      const saved = JSON.parse(localStorage.getItem(BUCKET_KEY));
      if (saved && saved.checks) return saved;
    } catch (e) {}
    return { checks: {}, custom: [] };
  });
  const [draft, setDraft] = useState('');
  const [showCert, setShowCert] = useState(false);
  const bonusRef = useRef(false);

  useEffect(() => {
    try { localStorage.setItem(BUCKET_KEY, JSON.stringify(state)); } catch (e) {}
  }, [state]);

  const items = VOCAB.map((v) => ({ id: v.id, text: v.phrase }))
    .concat(state.custom.map((t, i) => ({ id: 'custom' + i, text: t })));
  const checkedCount = items.filter((it) => state.checks[it.id]).length;

  function toggle(id, e) {
    const on = !state.checks[id];
    if (on) { SFX.star(); starPop(e.clientX, e.clientY); }
    else SFX.click();
    const next = { ...state, checks: { ...state.checks, [id]: on } };
    setState(next);
    const count = items.filter((it) => next.checks[it.id]).length;
    if (count >= 5 && !bonusRef.current) {
      bonusRef.current = true;
      earn(5);
      burstConfetti(28);
    }
  }
  function addCustom() {
    const t = draft.trim();
    if (!t || state.custom.length >= 3) return;
    SFX.correct();
    setState({ ...state, custom: [...state.custom, t] });
    setDraft('');
  }
  function finish() {
    SFX.win();
    burstConfetti(60);
    setShowCert(true);
  }

  return (
    <ActivityShell stepNo="7" title={(name || 'My') + (name ? "'s" : '') + ' Summer Bucket List'}
      instructions="Tap everything YOU want to do this summer. Add your own ideas too!">
      <div className="bucket-list">
        {items.map((it) => (
          <button key={it.id} type="button"
            className={'bucket-item' + (state.checks[it.id] ? ' bucket-item-on' : '')}
            onClick={(e) => toggle(it.id, e)}>
            <span className="bucket-box">{state.checks[it.id] ? '★' : ''}</span>
            <span className="bucket-text">I want to {it.text}</span>
          </button>
        ))}
      </div>
      {state.custom.length < 3 && (
        <div className="bucket-add">
          <span className="bucket-add-prefix">I want to</span>
          <input type="text" className="bucket-input" value={draft} maxLength={40}
            placeholder="your idea&#8230;"
            onChange={(e) => setDraft(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') addCustom(); }} />
          <button type="button" className="btn btn-add" onClick={addCustom} disabled={!draft.trim()}>+ Add</button>
        </div>
      )}
      <div className="activity-foot">
        <span className="foot-hint">{checkedCount} wishes picked {checkedCount >= 5 ? '— bonus ★★★★★!' : '(pick at least 3)'}</span>
        <button type="button" className="btn btn-next" disabled={checkedCount < 3} onClick={finish}>
          Finish! ★
        </button>
      </div>

      {showCert && (
        <div className="cert-overlay" data-screen-label="Certificate">
          <div className="cert">
            <div className="cert-sun"></div>
            {buddy && <Mascot className="cert-mascot" />}
            <div className="cert-kicker">Super Summer Star</div>
            <h2 className="cert-name">{name || 'Summer Friend'}</h2>
            <p className="cert-line">finished the Summer Bucket List worksheet<br />with <strong>{stars} stars ★</strong> and <strong>{checkedCount} summer wishes!</strong></p>
            <ul className="cert-list">
              {items.filter((it) => state.checks[it.id]).slice(0, 6).map((it) => (
                <li key={it.id}>★ {it.text}</li>
              ))}
            </ul>
            <div className="cert-actions no-print">
              <button type="button" className="btn btn-ghost" onClick={() => { SFX.click(); setShowCert(false); }}>Back</button>
              <button type="button" className="btn btn-next" onClick={() => window.print()}>Print my list</button>
            </div>
          </div>
        </div>
      )}
    </ActivityShell>
  );
}

Object.assign(window, { QuizActivity, BucketActivity });
