/* ミニテストページ — サーバー採点版 */

function Quiz({ nav, progress, lessonSlug, chapterId, completeLesson, markQuizPassed }) {
  const lessonStore = window.APP_DATA.lessons;
  const chapters    = window.APP_DATA.chapters;
  const detail      = lessonStore[lessonSlug];

  // selections[i] = ユーザーが選んだ選択肢インデックス（null = 未選択）
  const [current,    setCurrent]    = React.useState(0);
  const [selections, setSelections] = React.useState([]);
  const [phase,      setPhase]      = React.useState("quiz"); // "quiz" | "submitting" | "result"
  const [result,     setResult]     = React.useState(null);   // API レスポンス
  const [mood,       setMood]       = React.useState("happy");

  // 次のセクターを特定
  const ch         = chapters.find(function(c) { return c.id === chapterId; });
  const chLessons  = ch ? ch.lessons : [];
  const curIdx     = chLessons.findIndex(function(l) { return l.slug === lessonSlug; });
  const nextLesson = curIdx >= 0 && curIdx < chLessons.length - 1 ? chLessons[curIdx + 1] : null;

  if (!detail || !detail.quiz || detail.quiz.length === 0) {
    return (
      <div className="quiz-wrap">
        <QuizStyles />
        <div className="quiz-empty">
          <Mascot size={100} mood="think" />
          <p>このレッスンにはテストがありません。</p>
          <button className="btn btn-primary" onClick={() => nav.goBack()}>← 戻る</button>
        </div>
      </div>
    );
  }

  const questions = detail.quiz;
  const total     = questions.length;
  const q         = questions[current];
  const curSel    = selections[current] !== undefined ? selections[current] : null;
  const isLastQ   = current === total - 1;

  const handleSelect = (idx) => {
    if (curSel !== null) return;
    var newSels = selections.slice();
    newSels[current] = idx;
    setSelections(newSels);
  };

  const handleNext = () => {
    if (curSel === null) return;
    if (!isLastQ) {
      setCurrent(current + 1);
      setMood("happy");
      window.scrollTo({ top: 0, behavior: "smooth" });
    } else {
      // 最終問 → サーバーに採点リクエスト
      setPhase("submitting");
      fetch('/api/quiz-submit', {
        method:  'POST',
        headers: { 'Content-Type': 'application/json' },
        body:    JSON.stringify({ slug: lessonSlug, answers: selections }),
      })
        .then(function(res) { return res.json(); })
        .then(function(data) {
          if (data.error) {
            // エラー時はクイズ画面に戻す
            setPhase("quiz");
            console.error('[株次郎] 採点エラー:', data.error);
            return;
          }
          if (data.passed) {
            completeLesson(lessonSlug);  // UI の completed を更新（サーバーは quiz-submit で記録済み）
            markQuizPassed(lessonSlug);  // UI の quizPassed を更新
          }
          setResult(data);
          setPhase("result");
          setMood(data.passed ? "cheer" : "think");
          window.scrollTo({ top: 0, behavior: "smooth" });
        })
        .catch(function(err) {
          setPhase("quiz");
          console.error('[株次郎] 通信エラー:', err);
        });
    }
  };

  const handleRetry = () => {
    setCurrent(0);
    setSelections([]);
    setPhase("quiz");
    setResult(null);
    setMood("happy");
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  // ── 採点中 ──
  if (phase === "submitting") {
    return (
      <div className="quiz-wrap">
        <QuizStyles />
        <div className="quiz-empty">
          <Mascot size={100} mood="happy" />
          <p style={{ color: 'var(--navy-800)', fontWeight: 700, fontSize: '16px' }}>採点中…</p>
        </div>
      </div>
    );
  }

  // ── 結果画面 ──
  if (phase === "result" && result) {
    var passed    = result.passed;
    var score     = result.score;
    var passCount = result.passCount;
    var results   = result.results; // bool[]
    var pct       = Math.round(score / total * 100);

    var goNext = function() {
      if (!passed) return;
      if (nextLesson) {
        nav.goLesson(nextLesson.slug, chapterId);
      } else {
        nav.goBack();
      }
    };

    return (
      <div className="quiz-wrap">
        <QuizStyles />
        <div className="quiz-result">

          <Mascot size={100} mood={passed ? "cheer" : "think"} />

          {/* 合否バナー */}
          <div className={"quiz-verdict " + (passed ? "pass" : "fail")}>
            {passed ? "🎉 合格！" : "😢 不合格"}
          </div>

          {/* スコア */}
          <div className="quiz-score">
            <span className="quiz-score-num">{score}</span>
            <span className="quiz-score-sep"> / </span>
            <span className="quiz-score-den">{total}</span>
            <span className="quiz-score-label">問正解</span>
          </div>

          {/* 合格ライン */}
          <p className="quiz-pass-line">
            合格ライン：{passCount}問以上（{Math.round(passCount / total * 100)}%）
          </p>

          {/* スコアバー */}
          <div className="quiz-score-bar">
            <div
              className="quiz-score-fill"
              style={{
                width:      pct + "%",
                background: passed ? "var(--green-500, #22c55e)" : "#ef4444",
              }}
            />
            <div
              className="quiz-pass-marker"
              style={{ left: Math.round(passCount / total * 100) + "%" }}
            />
          </div>
          <p className="quiz-score-pct">{pct}%</p>

          {/* 結果メッセージ */}
          <p className="quiz-result-msg">
            {passed
              ? "すばらしい！次のセクターに進もう！"
              : "もう一度本文を読み直してから「やり直す」を押してみよう。"}
          </p>

          {/* 答え合わせ（正解インデックスは非公開・results の bool のみ使用） */}
          <div className="quiz-review">
            {questions.map(function(qr, i) {
              var ok         = results[i];
              var userAnsIdx = selections[i];
              var expList    = (window.QUIZ_EXPLANATIONS || {})[lessonSlug] || [];
              var exp        = expList[i];
              var expText    = exp ? (ok ? exp.correct : exp.incorrect) : null;
              return (
                <div key={i} className={"quiz-review-item " + (ok ? "ok" : "ng")}>
                  <span className="quiz-review-icon">{ok ? "✓" : "✗"}</span>
                  <div>
                    <div className="quiz-review-q">問{i + 1}：{qr.q}</div>
                    <div className="quiz-review-a">
                      <span className={ok ? "quiz-review-correct" : "quiz-review-your"}>
                        あなた：{qr.options[userAnsIdx] ?? "未回答"}
                      </span>
                    </div>
                    {expText && (
                      <div className="quiz-review-exp">株次郎：「{expText}」</div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>

          {/* ボタン群 */}
          <div className="quiz-result-btns">
            {!passed && (
              <button className="btn btn-retry" onClick={handleRetry}>
                🔄 やり直す
              </button>
            )}
            <button
              className={"btn btn-primary quiz-next-sector-btn " + (!passed ? "disabled" : "")}
              onClick={goNext}
              disabled={!passed}
              title={!passed ? "合格してから次に進めます" : ""}
            >
              {nextLesson ? "次のセクターへ進む →" : "チャプター完了！→"}
            </button>
            <button className="btn btn-secondary" onClick={() => nav.goBack()}>
              チャプターへ戻る
            </button>
          </div>
        </div>
      </div>
    );
  }

  // ── 問題画面 ──
  return (
    <div className="quiz-wrap">
      <QuizStyles />

      <div className="quiz-header">
        <button className="quiz-back" onClick={() => nav.goBack()}>← 戻る</button>
        <div className="quiz-progress-wrap">
          <div className="quiz-progress-bar">
            <div className="quiz-progress-fill" style={{ width: (current / total * 100) + "%" }} />
          </div>
          <span className="quiz-progress-txt">問 {current + 1} / {total}</span>
        </div>
      </div>

      <div className="quiz-body">
        {/* マスコット */}
        <div className="quiz-mascot-row">
          <Mascot size={72} mood={mood} />
          <div className="quiz-mascot-bubble">
            {curSel === null
              ? "さあ、考えてみよう！"
              : isLastQ
                ? "全部選んだね！「採点する」を押してね！"
                : "選んだね！次の問題へ進もう！"}
          </div>
        </div>

        {/* 問題文 */}
        <div className="quiz-question">
          <span className="quiz-q-num">問{current + 1}</span>
          <span className="quiz-q-text">{q.q}</span>
        </div>

        {/* 選択肢（回答前は通常、回答後は選択したものをハイライト） */}
        <div className="quiz-options">
          {q.options.map(function(opt, i) {
            var cls = "quiz-option";
            if (curSel !== null) {
              if (i === curSel) cls += " picked";
              else cls += " dim";
            }
            return (
              <button
                key={i}
                className={cls}
                onClick={() => handleSelect(i)}
                disabled={curSel !== null}
              >
                <span className="quiz-opt-label">{["A", "B", "C", "D"][i]}</span>
                <span>{opt}</span>
                {curSel !== null && i === curSel && <span className="quiz-opt-check">✓</span>}
              </button>
            );
          })}
        </div>

        {curSel !== null && (
          <button className="btn btn-primary quiz-next-btn" onClick={handleNext}>
            {isLastQ ? "採点する 🎯" : "次の問題へ →"}
          </button>
        )}
      </div>
    </div>
  );
}

function QuizStyles() {
  return (
    <style>{`
      .quiz-wrap {
        min-height: 100vh;
        background: var(--ink-50, #f8f9fa);
        display: flex; flex-direction: column; align-items: center;
        padding: 0 16px 80px;
      }

      /* ヘッダー */
      .quiz-header {
        width: 100%; max-width: 680px;
        display: flex; align-items: center; gap: 16px;
        padding: 20px 0 16px;
      }
      .quiz-back { color: var(--ink-500); font-size: 13px; cursor: pointer; white-space: nowrap; }
      .quiz-back:hover { color: var(--navy-900); }
      .quiz-progress-wrap { flex: 1; display: flex; align-items: center; gap: 10px; }
      .quiz-progress-bar { flex: 1; height: 6px; background: var(--ink-200); border-radius: 99px; overflow: hidden; }
      .quiz-progress-fill { height: 100%; background: var(--gold-400); border-radius: 99px; transition: width .3s; }
      .quiz-progress-txt { font-size: 12px; color: var(--ink-400); white-space: nowrap; }

      .quiz-body { width: 100%; max-width: 680px; }

      /* マスコット */
      .quiz-mascot-row { display: flex; align-items: flex-start; gap: 14px; margin-bottom: 24px; }
      .quiz-mascot-bubble {
        background: white; border-radius: 12px; padding: 14px 18px;
        font-size: 14px; line-height: 1.6; color: var(--navy-800);
        box-shadow: 0 1px 6px rgba(0,0,0,.07); flex: 1; position: relative;
      }
      .quiz-mascot-bubble::before {
        content: ""; position: absolute; left: -8px; top: 18px;
        border: 8px solid transparent; border-right-color: white; border-left: none;
      }

      /* 問題文 */
      .quiz-question {
        background: white; border-radius: 14px; padding: 24px 28px;
        margin-bottom: 20px; box-shadow: 0 2px 8px rgba(0,0,0,.07);
        display: flex; gap: 14px; align-items: flex-start;
      }
      .quiz-q-num {
        background: var(--navy-900); color: white; font-size: 12px; font-weight: 700;
        padding: 4px 10px; border-radius: 99px; flex-shrink: 0; margin-top: 2px;
      }
      .quiz-q-text { font-size: 16px; font-weight: 700; color: var(--navy-900); line-height: 1.6; }

      /* 選択肢 */
      .quiz-options { display: flex; flex-direction: column; gap: 10px; margin-bottom: 28px; }
      .quiz-option {
        display: flex; align-items: center; gap: 14px;
        background: white; border: 2px solid var(--ink-200);
        border-radius: 12px; padding: 14px 18px;
        font-size: 15px; color: var(--navy-800); cursor: pointer; text-align: left;
        transition: border-color .15s, background .15s; width: 100%;
      }
      .quiz-option:hover:not(:disabled) { border-color: var(--navy-400); background: var(--navy-50); }
      .quiz-option:disabled { cursor: default; }
      /* 選択済みハイライト（採点前：正誤不明のためネイビー系） */
      .quiz-option.picked { border-color: var(--navy-600, #2d4a7a); background: var(--navy-50, #eef1f8); }
      .quiz-option.picked .quiz-opt-label { background: var(--navy-700, #1e3a6e); color: white; }
      .quiz-option.dim { opacity: .4; }
      .quiz-opt-label {
        width: 28px; height: 28px; border-radius: 50%;
        background: var(--navy-100); color: var(--navy-700); font-size: 13px; font-weight: 700;
        display: flex; align-items: center; justify-content: center; flex-shrink: 0;
      }
      .quiz-opt-check { margin-left: auto; color: var(--navy-700, #1e3a6e); font-size: 18px; font-weight: 700; }

      .quiz-next-btn { width: 100%; padding: 14px; font-size: 16px; border-radius: 12px; }

      /* ── 結果画面 ── */
      .quiz-empty, .quiz-result {
        width: 100%; max-width: 600px;
        display: flex; flex-direction: column; align-items: center;
        gap: 14px; padding: 40px 0;
      }

      /* 合否バナー */
      .quiz-verdict {
        font-size: 26px; font-weight: 900; padding: 10px 36px;
        border-radius: 99px; letter-spacing: .02em;
      }
      .quiz-verdict.pass { background: var(--green-100, #dcfce7); color: var(--green-700, #15803d); }
      .quiz-verdict.fail { background: #fee2e2; color: #b91c1c; }

      /* スコア */
      .quiz-score { display: flex; align-items: baseline; gap: 4px; font-weight: 900; color: var(--navy-900); }
      .quiz-score-num   { font-size: 60px; line-height: 1; color: var(--gold-500, #f5a623); }
      .quiz-score-sep   { font-size: 28px; }
      .quiz-score-den   { font-size: 28px; }
      .quiz-score-label { font-size: 18px; margin-left: 4px; }

      /* 合格ライン */
      .quiz-pass-line {
        font-size: 13px; color: var(--ink-500); margin: 0; text-align: center;
        background: var(--ink-100); padding: 6px 16px; border-radius: 99px;
      }

      /* スコアバー */
      .quiz-score-bar {
        width: 100%; height: 12px; background: var(--ink-200);
        border-radius: 99px; overflow: visible; position: relative;
      }
      .quiz-score-fill { height: 100%; border-radius: 99px; transition: width .6s; }
      .quiz-pass-marker {
        position: absolute; top: -4px; height: 20px; width: 3px;
        background: var(--navy-900); border-radius: 2px; transform: translateX(-50%);
      }
      .quiz-score-pct { font-size: 13px; color: var(--ink-400); margin: 0; align-self: flex-end; }

      .quiz-result-msg { font-size: 15px; color: var(--ink-700); text-align: center; max-width: 440px; margin: 0; }

      /* 答え合わせ */
      .quiz-review { width: 100%; display: flex; flex-direction: column; gap: 8px; margin: 4px 0; }
      .quiz-review-item {
        display: flex; gap: 12px; padding: 12px 16px; border-radius: 10px;
        font-size: 13px; line-height: 1.5;
      }
      .quiz-review-item.ok { background: var(--green-50, #f0fdf4); }
      .quiz-review-item.ng { background: #fef2f2; }
      .quiz-review-icon { font-size: 16px; font-weight: 700; flex-shrink: 0; margin-top: 1px; }
      .quiz-review-item.ok .quiz-review-icon { color: var(--green-600, #16a34a); }
      .quiz-review-item.ng .quiz-review-icon { color: #dc2626; }
      .quiz-review-q { font-weight: 600; color: var(--navy-800); margin-bottom: 3px; }
      .quiz-review-correct { color: var(--green-700, #15803d); }
      .quiz-review-your    { color: #dc2626; }
      .quiz-review-exp {
        margin-top: 6px; font-size: 12px; line-height: 1.65;
        color: var(--ink-600, #4a5568);
        padding: 6px 10px; border-radius: 6px;
        background: rgba(0,0,0,.04);
      }

      /* ボタン群 */
      .quiz-result-btns {
        display: flex; flex-direction: column; gap: 10px;
        width: 100%; max-width: 400px; margin-top: 4px;
      }

      .btn-retry {
        background: white; color: var(--navy-800);
        border: 2px solid var(--navy-300, #90a8e8);
        padding: 13px 28px; border-radius: 99px;
        font-size: 15px; font-weight: 700; cursor: pointer; width: 100%;
        transition: background .15s;
      }
      .btn-retry:hover { background: var(--navy-50); }

      .quiz-next-sector-btn { padding: 14px 28px; font-size: 15px; width: 100%; border-radius: 12px; }
      .quiz-next-sector-btn.disabled {
        background: var(--ink-300); cursor: not-allowed; opacity: .6;
      }
      .quiz-next-sector-btn.disabled:hover { background: var(--ink-300); }

      .btn-secondary {
        background: white; color: var(--ink-600);
        border: 1px solid var(--ink-200);
        padding: 11px 28px; border-radius: 99px;
        font-size: 14px; font-weight: 600; cursor: pointer; width: 100%;
      }
      .btn-secondary:hover { background: var(--ink-50); }

      @media(max-width:768px){
        .quiz-wrap { padding: 0 12px 100px; }
        .quiz-header { padding: 14px 0 12px; }
        .quiz-question { padding: 16px 16px; }
        .quiz-q-text { font-size: 15px; }
        .quiz-option { padding: 12px 14px; font-size: 14px; }
        .quiz-mascot-bubble { font-size: 13px; padding: 12px 14px; }
        .quiz-score-num { font-size: 48px; }
        .quiz-verdict { font-size: 22px; padding: 8px 28px; }
        .quiz-result-btns { max-width: 100%; }
        .quiz-empty, .quiz-result { padding: 28px 0; }
      }
      @media(max-width:480px){
        .quiz-wrap { padding: 0 10px 100px; }
        .quiz-question { padding: 14px 12px; }
        .quiz-q-text { font-size: 14px; }
        .quiz-option { padding: 10px 12px; font-size: 13px; gap: 10px; }
        .quiz-score-num { font-size: 40px; }
        .quiz-verdict { font-size: 19px; }
      }
    `}</style>
  );
}

window.Quiz = Quiz;
