/* eslint-disable */
// Mode 2: Multiple choice — given the word + phonetic, pick the correct meaning

const choicesFor = (word, pool, n = 4) => {
  // Prefer enriched (with en/zh) distractors at same CEFR
  const sameLevel = pool.filter(w => w.id !== word.id && w.cefr === word.cefr && w.en && w.zh);
  const distractors = sameLevel
    .sort(() => Math.random() - 0.5)
    .slice(0, n - 1);
  return [...distractors, word].sort(() => Math.random() - 0.5);
};

const ChoiceMode = ({ word, pool, onGrade, onGradeReadyChange, onStar, starred }) => {
  const [picked, setPicked] = useState(null);
  const [choices, setChoices] = useState(() => choicesFor(word, pool));

  useEffect(() => {
    setPicked(null);
    onGradeReadyChange?.(false);
    setChoices(choicesFor(word, pool));
    const t = setTimeout(() => window.speak(word.word), 200);
    return () => clearTimeout(t);
  }, [word.id]);

  useEffect(() => {
    onGradeReadyChange?.(picked !== null);
  }, [picked, onGradeReadyChange]);

  const correctId = word.id;
  const isCorrect = picked === correctId;

  return (
    <div style={{ width:'100%', maxWidth: 640, margin:'0 auto' }}>
      <PaperCard rotate={-0.3} style={{ padding: '36px 40px', minHeight: 360 }}>
        {/* Header */}
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', position:'relative', zIndex:2 }}>
          <CEFRChip level={word.cefr}/>
          <div style={{ display:'flex', gap:4 }}>
            <SpeakerBtn text={word.word} size={20}/>
            <StarBtn active={starred} onClick={onStar}/>
          </div>
        </div>

        {/* Prompt */}
        <div style={{ textAlign:'center', padding:'20px 0 28px', position:'relative', zIndex:2 }}>
          <div style={{ fontSize:11, fontFamily:'var(--font-mono)', textTransform:'uppercase', letterSpacing:'0.2em', color:'var(--ink-faded)', marginBottom:14 }}>
            选择正确的释义
          </div>
          <div className="serif" style={{ fontSize: 56, fontWeight:500, lineHeight:1 }}>{word.word}</div>
          <div className="phon" style={{ marginTop:8, fontSize:18 }}>{word.phonetic}</div>
          <div style={{ marginTop:6, color:'var(--ink-faded)', fontSize:12, fontFamily:'var(--font-mono)', textTransform:'uppercase', letterSpacing:'0.1em' }}>
            {word.pos}
          </div>
        </div>

        <hr className="rule-double" style={{ margin:'0 0 20px', position:'relative', zIndex:2 }}/>

        {/* Choices */}
        <div style={{ display:'grid', gap: 10, position:'relative', zIndex:2 }}>
          {choices.map((c, i) => {
            const isPicked = picked === c.id;
            const isThisCorrect = c.id === correctId;
            const showState = picked !== null;
            let border = 'var(--rule)';
            let bg = 'var(--paper-1)';
            let inkColor = 'var(--ink)';
            if (showState) {
              if (isThisCorrect) { border = 'var(--green-ok)'; bg = 'rgba(90,115,57,0.08)'; }
              else if (isPicked) { border = 'var(--red-stamp)'; bg = 'rgba(168,52,31,0.08)'; }
              else { inkColor = 'var(--ink-faded)'; }
            }
            return (
              <button key={c.id}
                disabled={showState}
                onClick={() => setPicked(c.id)}
                style={{
                  display:'flex', gap:12, alignItems:'center',
                  textAlign:'left',
                  padding:'12px 16px',
                  background: bg,
                  border:`1px solid ${border}`,
                  borderRadius: 3,
                  cursor: showState ? 'default' : 'pointer',
                  fontFamily:'var(--font-sans)',
                  color: inkColor,
                  transition: 'background 0.1s',
                }}
                onMouseOver={e => { if (!showState) e.currentTarget.style.background = 'var(--paper-2)'; }}
                onMouseOut={e => { if (!showState) e.currentTarget.style.background = bg; }}
              >
                <span style={{
                  width: 22, height:22, borderRadius:2,
                  border: `1.5px solid ${border}`,
                  display:'inline-flex', alignItems:'center', justifyContent:'center',
                  fontFamily:'var(--font-mono)', fontSize:11, fontWeight:700,
                  flexShrink:0,
                }}>{String.fromCharCode(65+i)}</span>
                <span style={{ flex:1 }}>
                  <span className="serif" style={{ fontSize:16, lineHeight:1.4 }}>{c.en}</span>
                  {showState && (
                    <span style={{ display:'block', fontSize:13, color:'var(--ink-faded)', marginTop:2 }}>{c.zh}</span>
                  )}
                </span>
                {showState && isThisCorrect && <Tick color="var(--green-ok)"/>}
                {showState && isPicked && !isThisCorrect && <Cross color="var(--red-stamp)"/>}
              </button>
            );
          })}
        </div>

        {/* Marginalia stamp on result */}
        {picked !== null && (
          <div style={{ marginTop:18, display:'flex', justifyContent:'center', position:'relative', zIndex:2 }}>
            <span className="stamp" style={{ color: isCorrect ? 'var(--green-ok)' : 'var(--red-stamp)' }}>
              {isCorrect ? 'Correct' : 'Try again'}
            </span>
          </div>
        )}
      </PaperCard>

      {/* Grade buttons appear after pick */}
      {picked !== null && (
        <div style={{ display:'flex', justifyContent:'center', gap:10, marginTop:20 }}>
          <button className="btn ghost" onClick={() => onGrade('again')}>Again</button>
          {isCorrect ? (
            <>
              <button className="btn" onClick={() => onGrade('hard')}>Hard</button>
              <button className="btn primary" onClick={() => onGrade('good')}>Good</button>
              <button className="btn" onClick={() => onGrade('easy')}>Easy</button>
            </>
          ) : (
            <button className="btn primary" onClick={() => onGrade('again')}>Continue</button>
          )}
        </div>
      )}
    </div>
  );
};

const Tick = ({ color }) => (
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5"/></svg>
);
const Cross = ({ color }) => (
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6L6 18M6 6l12 12"/></svg>
);

window.ChoiceMode = ChoiceMode;
