// exam.jsx — そうきくんのパパの審査. Questions + grading come from the server
// (GET /api/exam returns NO answer key; POST /api/exam/submit grades server-side).
(function () {
  const { useState } = React;
  const { Icon } = window;

  // Intro copy is branding (safe to keep client-side); questions/answers are NOT.
  const INTRO = {
    title: 'そうきくんのパパの審査',
    lead: 'ぱぱFMは「いい曲を、ちゃんとした言葉で」みんなにすすめる場所。投稿できるのは審査を突破した人だけ。リプはいつでも自由。',
    rules: [
      '選択式。規定数の正解で合格。',
      '合格すると「投稿」が解放されます。',
      '不合格でも何回でも再挑戦OK。',
      'リプ（返信）は審査なしで誰でもできます。',
    ],
  };
  const PASS_LINE = '“聴く人の一日のために。” ようこそ、パパDJ。— そうきくんのパパ';
  const FAIL_LINE = 'リプはいつでもできる。タイムラインを浴びて、出直しておいで。';

  function ExamScreen({ app }) {
    const T = app.theme;
    const [stage, setStage] = useState(app.user.passed ? 'passed' : 'intro'); // intro|quiz|result|passed
    const [exam, setExam] = useState(null);      // {pass_needed, questions}
    const [qi, setQi] = useState(0);
    const [picks, setPicks] = useState([]);
    const [result, setResult] = useState(null);  // server response
    const [busy, setBusy] = useState(false);

    const loadExam = async () => {
      const d = await window.PFApi.get('/exam');
      setExam(d); setPicks(new Array(d.questions.length).fill(null)); setQi(0); setResult(null);
    };

    const begin = async () => { await loadExam(); setStage('quiz'); };

    const submit = async (finalPicks) => {
      setBusy(true);
      try {
        const r = await window.PFApi.post('/exam/submit', { picks: finalPicks });
        setResult(r);
        await app.refreshMe();
        setStage('result');
      } finally { setBusy(false); }
    };

    // ── already passed ──
    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, position: 'relative', overflow: 'hidden', textAlign: 'center' }}>
            <div style={{ position: 'absolute', inset: 0, background: `radial-gradient(100% 80% at 50% 0%, ${T.accent}26, transparent 65%)` }} />
            <div style={{ position: 'relative' }}>
              <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 }}>ベストスコア {app.user.exam_best}。投稿はいつでもできます。</p>
              <p style={{ color: T.accent, fontSize: 13.5, fontWeight: 700, marginTop: 14 }}>“聴く人の一日のために。”</p>
            </div>
          </div>
          <button onClick={() => { app.closeExam(); app.compose(); }} style={primaryBtn(T)}>新しい一曲を投稿</button>
          <button onClick={begin} style={ghostBtn(T)}>もう一度審査を受ける</button>
        </div>
      );
    }

    if (stage === 'intro') {
      return (
        <div style={{ padding: '8px 18px 40px' }}>
          <div style={{ border: `1px solid ${T.border}`, borderRadius: 20, background: T.surface, padding: 22, marginTop: 8, position: 'relative', overflow: 'hidden' }}>
            <div style={{ position: 'absolute', inset: 0, background: `radial-gradient(120% 80% at 100% 0%, ${T.accent}22, transparent 60%)` }} />
            <div style={{ position: 'relative' }}>
              <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: 26, fontWeight: 900, color: T.text, margin: '12px 0 8px', lineHeight: 1.3 }}>{INTRO.title}</h1>
              <p style={{ color: T.sub, lineHeight: 1.7, fontSize: 14.5, margin: 0 }}>{INTRO.lead}</p>
            </div>
          </div>
          <div style={{ marginTop: 18 }}>
            {INTRO.rules.map((r, i) => (
              <div key={i} style={{ display: 'flex', gap: 11, padding: '11px 4px', borderBottom: i < INTRO.rules.length - 1 ? `1px solid ${T.border}` : 'none' }}>
                <span style={{ color: T.accent, marginTop: 1, flexShrink: 0 }}><Icon.check size={18} /></span>
                <span style={{ color: T.text, fontSize: 14.5, lineHeight: 1.5 }}>{r}</span>
              </div>
            ))}
          </div>
          <button onClick={begin} style={primaryBtn(T)}>審査を受ける</button>
          <p style={{ textAlign: 'center', color: T.faint, fontSize: 12.5, marginTop: 14, lineHeight: 1.6 }}>
            リプ（返信）は審査なしで誰でもOK。<br/>投稿だけが、この先にある。
          </p>
        </div>
      );
    }

    if (stage === 'quiz' && exam) {
      const q = exam.questions[qi];
      const total = exam.questions.length;
      const selected = 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) => {
              const on = selected === i;
              return (
                <button key={i} onClick={() => choose(i)} style={{
                  display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left',
                  background: on ? T.surface2 : T.surface, border: `1.5px solid ${on ? T.accent : T.border}`,
                  borderRadius: 14, padding: '14px 16px', color: T.text, font: 'inherit', fontSize: 15, lineHeight: 1.45, cursor: 'pointer',
                }}>
                  <span style={{ flex: 1 }}>{c}</span>
                  {on && <span style={{ color: T.accent, flexShrink: 0 }}><Icon.check size={18} /></span>}
                </button>
              );
            })}
          </div>
          <button onClick={next} disabled={selected == null || busy} style={{ ...primaryBtn(T), opacity: (selected == null || busy) ? 0.4 : 1, cursor: (selected == null || busy) ? 'not-allowed' : 'pointer' }}>
            {busy ? '採点中…' : (qi + 1 < total ? '次へ' : '採点する')}
          </button>
        </div>
      );
    }

    if (stage === 'result' && result) {
      const passed = 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: passed ? `${T.accent}22` : T.surface, color: passed ? T.accent : T.faint, border: `1.5px solid ${passed ? T.accent : T.border}` }}>
            {passed ? <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' }}>{passed ? '合格！' : 'もう一歩。'}</h1>
          <p style={{ color: T.sub, fontSize: 15, lineHeight: 1.65, margin: '0 auto', maxWidth: 300 }}>{passed ? 'ぱぱFMの投稿が解放されました。' : '惜しい。理由を持って選ぶ感覚を、もう一度。'}</p>
          <div style={{ marginTop: 22, padding: 18, borderRadius: 16, textAlign: 'left', background: T.surface, border: `1px solid ${T.border}`, display: 'flex', gap: 12, alignItems: 'flex-start' }}>
            <span style={{ color: T.accent, flexShrink: 0, marginTop: 2 }}><Icon.sparkle size={20} /></span>
            <p style={{ color: T.text, fontSize: 14.5, lineHeight: 1.7, margin: 0 }}>{passed ? PASS_LINE : FAIL_LINE}</p>
          </div>
          {passed ? (
            <button onClick={() => { app.closeExam(); app.compose(); }} style={primaryBtn(T)}>さっそく投稿する</button>
          ) : (
            <button onClick={begin} style={primaryBtn(T)}>もう一度挑戦する</button>
          )}
          <button onClick={() => app.closeExam()} style={ghostBtn(T)}>タイムラインへ</button>
        </div>
      );
    }

    return <div style={{ padding: 40, color: T.faint, textAlign: 'center' }}>読み込み中…</div>;
  }

  function primaryBtn(T) {
    return { 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` };
  }
  function ghostBtn(T) {
    return { 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;
})();
