// exam.jsx — group-scoped screening. GET /groups/:gid/exam (no answer key),
// POST /groups/:gid/exam/submit (server-graded). window.ExamScreen.
(function () {
  const { useState } = React;
  const { Icon } = window;

  function ExamScreen({ app }) {
    const T = app.theme;
    const passed = !!app.membership?.passed;
    const examBest = app.membership?.exam_best || 0;
    const [stage, setStage] = useState(passed ? 'passed' : 'intro');
    const [exam, setExam] = useState(null);
    const [qi, setQi] = useState(0);
    const [picks, setPicks] = useState([]);
    const [result, setResult] = useState(null);
    const [busy, setBusy] = useState(false);
    const base = `/groups/${app.gid}`;

    const begin = async () => { const d = await window.PFApi.get(`${base}/exam`); setExam(d); setPicks(new Array(d.questions.length).fill(null)); setQi(0); setResult(null); setStage('quiz'); };
    const submit = async (finalPicks) => {
      setBusy(true);
      try { const r = await window.PFApi.post(`${base}/exam/submit`, { picks: finalPicks }); setResult(r); await app.refreshMembership(); setStage('result'); }
      finally { setBusy(false); }
    };

    if (stage === 'passed') {
      return (
        <div style={{ padding: '8px 18px 40px' }}>
          <div style={{ border: `1px solid ${T.accent}55`, borderRadius: 20, background: T.surface, padding: 24, marginTop: 8, textAlign: 'center' }}>
            <div style={{ color: T.accent, display: 'inline-flex' }}><Icon.badgeFill size={52} /></div>
            <h1 style={{ fontFamily: T.display, fontSize: 24, fontWeight: 900, color: T.text, margin: '12px 0 6px' }}>審査 合格ずみ</h1>
            <p style={{ color: T.sub, fontSize: 14.5, lineHeight: 1.65, margin: 0 }}>ベストスコア {examBest}。投稿はいつでもできます。</p>
            <p style={{ color: T.accent, fontSize: 13.5, fontWeight: 700, marginTop: 14 }}>“聴く人の一日のために。”</p>
          </div>
          <button onClick={() => { app.closeExam(); app.compose(); }} style={pb(T)}>新しい一曲を投稿</button>
          <button onClick={begin} style={gb(T)}>もう一度審査を受ける</button>
        </div>
      );
    }
    if (stage === 'intro') {
      const rules = ['選択式。規定数の正解で合格。', '合格すると「投稿」が解放されます。', '不合格でも何回でも再挑戦OK。', 'リプ（返信）は審査なしで誰でもできます。'];
      return (
        <div style={{ padding: '8px 18px 40px' }}>
          <div style={{ border: `1px solid ${T.border}`, borderRadius: 20, background: T.surface, padding: 22, marginTop: 8 }}>
            <div style={{ color: T.accent, display: 'flex', alignItems: 'center', gap: 8 }}><Icon.badge size={26} /><span style={{ fontWeight: 800, fontSize: 13, letterSpacing: 1 }}>SCREENING</span></div>
            <h1 style={{ fontFamily: T.display, fontSize: 24, fontWeight: 900, color: T.text, margin: '12px 0 8px', lineHeight: 1.3 }}>{app.examTitle}</h1>
            <p style={{ color: T.sub, lineHeight: 1.7, fontSize: 14.5, margin: 0 }}>いい曲を、ちゃんとした言葉で。投稿できるのは審査を突破した人だけ。リプはいつでも自由。</p>
          </div>
          <div style={{ marginTop: 18 }}>{rules.map((r, i) => (
            <div key={i} style={{ display: 'flex', gap: 11, padding: '11px 4px', borderBottom: i < rules.length - 1 ? `1px solid ${T.border}` : 'none' }}>
              <span style={{ color: T.accent, flexShrink: 0 }}><Icon.check size={18} /></span><span style={{ color: T.text, fontSize: 14.5 }}>{r}</span>
            </div>))}</div>
          <button onClick={begin} style={pb(T)}>審査を受ける</button>
        </div>
      );
    }
    if (stage === 'quiz' && exam) {
      const q = exam.questions[qi]; const total = exam.questions.length; const sel = picks[qi];
      const choose = (i) => { const n = [...picks]; n[qi] = i; setPicks(n); };
      const next = () => { if (qi + 1 < total) setQi(qi + 1); else submit(picks); };
      return (
        <div style={{ padding: '8px 18px 40px' }}>
          <div style={{ display: 'flex', gap: 5, margin: '6px 0 20px' }}>{exam.questions.map((_, i) => <div key={i} style={{ flex: 1, height: 4, borderRadius: 2, background: i <= qi ? T.accent : T.border }} />)}</div>
          <div style={{ color: T.faint, fontSize: 12.5, fontWeight: 700, letterSpacing: 1 }}>Q{qi + 1} / {total}</div>
          <h2 style={{ color: T.text, fontSize: 20, fontWeight: 800, lineHeight: 1.5, margin: '8px 0 20px' }}>{q.question}</h2>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>{q.choices.map((c, i) => (
            <button key={i} onClick={() => choose(i)} style={{ display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left', background: sel === i ? T.surface2 : T.surface, border: `1.5px solid ${sel === i ? T.accent : T.border}`, borderRadius: 14, padding: '14px 16px', color: T.text, font: 'inherit', fontSize: 15, cursor: 'pointer' }}>
              <span style={{ flex: 1 }}>{c}</span>{sel === i && <span style={{ color: T.accent }}><Icon.check size={18} /></span>}
            </button>))}</div>
          <button onClick={next} disabled={sel == null || busy} style={{ ...pb(T), opacity: (sel == null || busy) ? 0.4 : 1 }}>{busy ? '採点中…' : (qi + 1 < total ? '次へ' : '採点する')}</button>
        </div>
      );
    }
    if (stage === 'result' && result) {
      const ok = result.passed;
      return (
        <div style={{ padding: '20px 22px 40px', textAlign: 'center' }}>
          <div style={{ width: 96, height: 96, borderRadius: '50%', margin: '12px auto 0', display: 'flex', alignItems: 'center', justifyContent: 'center', background: ok ? `${T.accent}22` : T.surface, color: ok ? T.accent : T.faint, border: `1.5px solid ${ok ? T.accent : T.border}` }}>{ok ? <Icon.badgeFill size={48} /> : <Icon.badge size={48} />}</div>
          <div style={{ fontSize: 13, fontWeight: 800, letterSpacing: 2, color: T.faint, marginTop: 18 }}>{result.score} / {result.total} 正解</div>
          <h1 style={{ fontFamily: T.display, fontSize: 30, fontWeight: 900, color: T.text, margin: '8px 0 10px' }}>{ok ? '合格！' : 'もう一歩。'}</h1>
          <p style={{ color: T.sub, fontSize: 15, lineHeight: 1.65, maxWidth: 300, margin: '0 auto' }}>{ok ? '投稿が解放されました。' : '理由を持って選ぶ感覚を、もう一度。'}</p>
          {ok ? <button onClick={() => { app.closeExam(); app.compose(); }} style={pb(T)}>さっそく投稿する</button>
              : <button onClick={begin} style={pb(T)}>もう一度挑戦する</button>}
          <button onClick={() => app.closeExam()} style={gb(T)}>タイムラインへ</button>
        </div>
      );
    }
    return <div style={{ padding: 40, color: T.faint, textAlign: 'center' }}>読み込み中…</div>;
  }
  const pb = (T) => ({ width: '100%', marginTop: 22, padding: '15px', borderRadius: 14, border: 'none', background: T.accent, color: '#fff', fontWeight: 800, fontSize: 16, cursor: 'pointer', fontFamily: 'inherit', boxShadow: `0 6px 18px ${T.accent}55` });
  const gb = (T) => ({ width: '100%', marginTop: 10, padding: '13px', borderRadius: 14, border: `1px solid ${T.border}`, background: 'none', color: T.sub, fontWeight: 700, fontSize: 14.5, cursor: 'pointer', fontFamily: 'inherit' });
  window.ExamScreen = ExamScreen;
})();
