/* 投資スタイル診断（応用コース7手法のうちどれが合うか、株次郎が診断） */

/* ── 診断対象の7手法（page-applied.jsx の buildApCourses と対応） ── */
const STYLE_QUIZ_METHODS = [
  {
    id: "tc-1", prefix: "tc1", icon: "📈",
    short: "テクニカル分析実践攻略",
    comment: "まずはこれ！チャートの基本をしっかり固めながら、テクニカル分析の型を身につけよう。",
  },
  {
    id: "tc-2", prefix: "tc2", icon: "🚀",
    short: "初動キャッチ手法",
    comment: "トレンドの“始まり”を逃さないキミにぴったり。初動をつかむセンスを磨こう！",
  },
  {
    id: "tc-3", prefix: "tc3", icon: "🔍",
    short: "複数視点分析手法",
    comment: "一つの視点にとらわれず、複数の角度からじっくり検証するタイプだね。精度重視の分析が向いてるよ。",
  },
  {
    id: "fc-1", prefix: "fc1", icon: "🏛",
    short: "ファンダメンタル分析実践攻略",
    comment: "まずはこれ！企業の数字を読み解く基本を固めながら、ファンダメンタル分析の型を身につけよう。",
  },
  {
    id: "fc-2", prefix: "fc2", icon: "💡",
    short: "テーマ株投資手法",
    comment: "世の中のトレンドを敏感にキャッチできるキミに◎。テーマ株で時代の波に乗ろう！",
  },
  {
    id: "fc-3", prefix: "fc3", icon: "🌱",
    short: "成長株投資手法",
    comment: "じっくり会社を見極めて、これから伸びる会社に投資するのが向いてる。腰を据えた投資向き。",
  },
  {
    id: "fc-4", prefix: "fc4", icon: "💎",
    short: "テンバガー発掘手法",
    comment: "大きな夢を追いかけるタイプ！ただしリスク管理は必須。守りを固めて大化け株を狙おう。",
  },
  {
    id: "dc-1", prefix: "dc1", icon: "💴",
    short: "配当株投資コース①",
    comment: "配当金で安定収入を得る“じっくり型”の投資法。値動きに一喜一憂せず、じっくり育てるのが向いてるよ。",
  },
];

/* ── 質問データ（8問・選択肢ごとに7手法へのスコア配点） ── */
const STYLE_QUIZ_QUESTIONS = [
  {
    mood: "happy",
    lead: "まずは時間のこと、教えて！",
    q: "投資にどれくらい時間をかけられそう？",
    options: [
      { label: "毎日こまめにチャートをチェックしたい", scores: { "tc-2": 3, "tc-1": 2, "tc-3": 1 } },
      { label: "平日はたまに、休日にじっくり", scores: { "tc-1": 2, "tc-3": 2, "fc-2": 2, "dc-1": 1 } },
      { label: "忙しいので週1回くらいで十分", scores: { "fc-1": 3, "fc-3": 2, "dc-1": 2 } },
      { label: "月1回くらいでもOK、じっくり長期保有したい", scores: { "fc-1": 2, "fc-3": 3, "dc-1": 3 } },
    ],
  },
  {
    mood: "think",
    lead: "次はリスクの好みかな。",
    q: "どれくらいのリスクなら受け入れられる？",
    options: [
      { label: "大きく狙いたい！大化けを夢見てる", scores: { "fc-4": 3, "tc-2": 2 } },
      { label: "そこそこ増えればOK、無理はしたくない", scores: { "tc-1": 2, "fc-1": 2, "fc-3": 1, "dc-1": 2 } },
      { label: "とにかく安定重視、大きな損はしたくない", scores: { "fc-1": 3, "tc-3": 2, "tc-1": 1, "dc-1": 3 } },
      { label: "リスクとリターンのバランスを取りたい", scores: { "fc-3": 3, "tc-3": 2, "fc-2": 1, "dc-1": 1 } },
    ],
  },
  {
    mood: "happy",
    lead: "分析するなら、どっちが好き？",
    q: "分析の好みを教えて！",
    options: [
      { label: "ローソク足やチャートの形を見るのが好き", scores: { "tc-1": 3, "tc-2": 3, "tc-3": 2 } },
      { label: "会社の決算書や数字を見るのが好き", scores: { "fc-1": 3, "fc-3": 3, "fc-4": 1, "dc-1": 2 } },
      { label: "ニュースや世の中のトレンドを追うのが好き", scores: { "fc-2": 3, "fc-4": 1 } },
      { label: "複数のデータを組み合わせて考えるのが好き", scores: { "tc-3": 3, "fc-3": 2, "dc-1": 1 } },
    ],
  },
  {
    mood: "wink",
    lead: "どれくらい持ち続けたい？",
    q: "株を持つ期間のイメージは？",
    options: [
      { label: "数日〜数週間の短期で売買したい", scores: { "tc-2": 3, "tc-1": 2 } },
      { label: "数ヶ月くらいの中期でじっくり", scores: { "tc-3": 2, "fc-2": 3, "fc-3": 2, "dc-1": 1 } },
      { label: "年単位でどっしり長期保有したい", scores: { "fc-1": 3, "fc-3": 2, "dc-1": 3 } },
      { label: "チャンスがあれば短期、無ければ長期も", scores: { "tc-1": 2, "fc-4": 2, "fc-3": 1, "dc-1": 1 } },
    ],
  },
  {
    mood: "happy",
    lead: "どんな会社が気になる？",
    q: "興味がある企業のタイプは？",
    options: [
      { label: "誰もが知ってる大企業・有名企業", scores: { "fc-1": 3, "tc-1": 2, "dc-1": 3 } },
      { label: "これから伸びそうな成長企業", scores: { "fc-3": 3, "fc-2": 1 } },
      { label: "上場したばかりの新興・IPO企業", scores: { "fc-4": 3 } },
      { label: "話題のテーマ（AI・EVなど）に関連する企業", scores: { "fc-2": 3 } },
    ],
  },
  {
    mood: "think",
    lead: "性格的なところも聞かせて。",
    q: "決断のしかたは、どっちに近い？",
    options: [
      { label: "即断即決タイプ、直感を信じる", scores: { "tc-2": 3, "fc-4": 2 } },
      { label: "じっくり調べてから決めるタイプ", scores: { "fc-1": 2, "fc-3": 2, "tc-3": 2, "dc-1": 2 } },
      { label: "ルールを決めたらきっちり守るタイプ", scores: { "tc-1": 2, "fc-4": 2, "tc-3": 1, "dc-1": 1 } },
      { label: "色々な視点から比較検討したい", scores: { "tc-3": 3, "fc-2": 1 } },
    ],
  },
  {
    mood: "happy",
    lead: "銘柄選びで一番大事にしたいのは？",
    q: "株を選ぶとき、一番重視したいことは？",
    options: [
      { label: "チャートの形（トレンドやパターン）", scores: { "tc-1": 3, "tc-2": 2 } },
      { label: "会社の業績・利益の伸び", scores: { "fc-3": 3, "fc-1": 2, "dc-1": 2 } },
      { label: "話題性・注目度の高さ", scores: { "fc-2": 3, "fc-4": 1 } },
      { label: "割安かどうか（お買い得感）", scores: { "fc-1": 2, "fc-3": 2, "fc-4": 1, "dc-1": 1 } },
    ],
  },
  {
    mood: "cheer",
    lead: "最後の質問だよ！",
    q: "将来、どんな投資家になりたい？",
    options: [
      { label: "チャートを読みこなすトレーダー", scores: { "tc-2": 3, "tc-1": 2, "tc-3": 1 } },
      { label: "優良企業を見抜く目利き投資家", scores: { "fc-1": 3, "fc-3": 2, "dc-1": 2 } },
      { label: "トレンドをいち早く掴む投資家", scores: { "fc-2": 3, "tc-2": 1 } },
      { label: "大化け株を発掘する投資家", scores: { "fc-4": 3 } },
    ],
  },
];

function StyleQuizPage({ nav, progress }) {
  const chapters = window.APP_DATA.chapters;

  const [current,  setCurrent]  = React.useState(0);
  const [answers,  setAnswers]  = React.useState([]); // answers[i] = 選んだ選択肢index
  const [phase,    setPhase]    = React.useState("quiz"); // "quiz" | "result"

  const total   = STYLE_QUIZ_QUESTIONS.length;
  const qData   = STYLE_QUIZ_QUESTIONS[current];
  const curSel  = answers[current] !== undefined ? answers[current] : null;
  const isLastQ = current === total - 1;

  const handleSelect = (idx) => {
    if (curSel !== null) return;
    var next = answers.slice();
    next[current] = idx;
    setAnswers(next);
  };

  const handleNext = () => {
    if (curSel === null) return;
    if (!isLastQ) {
      setCurrent(current + 1);
      window.scrollTo({ top: 0, behavior: "smooth" });
    } else {
      setPhase("result");
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  };

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

  // ── 集計：7手法のスコアを合計してTOP3を出す ──
  const top3 = React.useMemo(() => {
    if (phase !== "result") return [];
    var scores = {};
    STYLE_QUIZ_METHODS.forEach(function(m) { scores[m.id] = 0; });
    answers.forEach(function(optIdx, qIdx) {
      var opt = STYLE_QUIZ_QUESTIONS[qIdx].options[optIdx];
      if (!opt) return;
      Object.keys(opt.scores).forEach(function(mid) {
        scores[mid] = (scores[mid] || 0) + opt.scores[mid];
      });
    });
    return STYLE_QUIZ_METHODS
      .map(function(m) { return { ...m, score: scores[m.id] || 0 }; })
      .sort(function(a, b) { return b.score - a.score; })
      .slice(0, 3);
  }, [phase, answers]);

  const startCourse = (method) => {
    var ch = chapters.find(function(c) { return c.prefix === method.prefix; });
    if (ch && ch.lessons && ch.lessons.length > 0) {
      nav.goLesson(ch.lessons[0].slug, ch.id);
    } else {
      nav.goApplied();
    }
  };

  // ── 結果画面 ──
  if (phase === "result") {
    return (
      <div className="sq-wrap">
        <StyleQuizStyles />
        <div className="sq-result">
          <Mascot size={92} mood="cheer" />
          <h1 className="sq-result-title">あなたにおすすめの投資法 TOP3</h1>
          <p className="sq-result-sub">迷ったら参考にしてね。もちろん他の手法を選んでもOKだよ！</p>

          <div className="sq-result-list">
            {top3.map(function(m, i) {
              return (
                <div key={m.id} className={"sq-result-card sq-rank-" + (i + 1)}>
                  <div className="sq-rank-badge">{i + 1}位</div>
                  <div className="sq-result-card-head">
                    <span className="sq-result-icon">{m.icon}</span>
                    <span className="sq-result-name">{m.short}</span>
                  </div>
                  <div className="sq-result-comment">
                    <Mascot size={40} mood="happy" />
                    <p>{m.comment}</p>
                  </div>
                  <button className="btn btn-primary sq-start-btn" onClick={() => startCourse(m)}>
                    このコースを始める →
                  </button>
                </div>
              );
            })}
          </div>

          <div className="sq-result-btns">
            <button className="btn-retry" onClick={handleRetry}>🔄 もう一度診断する</button>
            <button className="btn-secondary" onClick={() => nav.goApplied()}>応用コース一覧へ戻る</button>
          </div>
        </div>
      </div>
    );
  }

  // ── 質問画面 ──
  return (
    <div className="sq-wrap">
      <StyleQuizStyles />

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

      <div className="sq-body">
        <div className="sq-mascot-row">
          <Mascot size={72} mood={qData.mood} />
          <div className="sq-mascot-bubble">{qData.lead}</div>
        </div>

        <div className="sq-question">
          <span className="sq-q-num">Q{current + 1}</span>
          <span className="sq-q-text">{qData.q}</span>
        </div>

        <div className="sq-options">
          {qData.options.map(function(opt, i) {
            var cls = "sq-option";
            if (curSel !== null) cls += i === curSel ? " picked" : " dim";
            return (
              <button
                key={i}
                className={cls}
                onClick={() => handleSelect(i)}
                disabled={curSel !== null}
              >
                <span className="sq-opt-label">{["A", "B", "C", "D"][i]}</span>
                <span>{opt.label}</span>
                {curSel !== null && i === curSel && <span className="sq-opt-check">✓</span>}
              </button>
            );
          })}
        </div>

        {curSel !== null && (
          <button className="btn btn-primary sq-next-btn" onClick={handleNext}>
            {isLastQ ? "診断結果を見る 🔮" : "次の質問へ →"}
          </button>
        )}
      </div>
    </div>
  );
}

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

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

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

      .sq-mascot-row { display: flex; align-items: flex-start; gap: 14px; margin-bottom: 24px; }
      .sq-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;
      }
      .sq-mascot-bubble::before {
        content: ""; position: absolute; left: -8px; top: 18px;
        border: 8px solid transparent; border-right-color: white; border-left: none;
      }

      .sq-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;
      }
      .sq-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;
      }
      .sq-q-text { font-size: 16px; font-weight: 700; color: var(--navy-900); line-height: 1.6; }

      .sq-options { display: flex; flex-direction: column; gap: 10px; margin-bottom: 28px; }
      .sq-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%;
      }
      .sq-option:hover:not(:disabled) { border-color: var(--navy-400); background: var(--navy-50); }
      .sq-option:disabled { cursor: default; }
      .sq-option.picked { border-color: var(--navy-600, #2d4a7a); background: var(--navy-50, #eef1f8); }
      .sq-option.picked .sq-opt-label { background: var(--navy-700, #1e3a6e); color: white; }
      .sq-option.dim { opacity: .4; }
      .sq-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;
      }
      .sq-opt-check { margin-left: auto; color: var(--navy-700, #1e3a6e); font-size: 18px; font-weight: 700; }

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

      /* ── 結果画面 ── */
      .sq-result {
        width: 100%; max-width: 600px;
        display: flex; flex-direction: column; align-items: center;
        gap: 10px; padding: 40px 0;
      }
      .sq-result-title { font-size: 22px; font-weight: 900; color: var(--navy-900); margin: 4px 0 0; text-align: center; }
      .sq-result-sub { font-size: 13px; color: var(--ink-500); margin: 0 0 8px; text-align: center; }

      .sq-result-list { width: 100%; display: flex; flex-direction: column; gap: 16px; margin-bottom: 8px; }
      .sq-result-card {
        background: white; border-radius: 16px; padding: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,.07); position: relative;
        border: 2px solid transparent;
      }
      .sq-rank-1 { border-color: var(--gold-400, #ffc15c); }
      .sq-rank-badge {
        position: absolute; top: -12px; left: 18px;
        background: var(--navy-900); color: white; font-size: 12px; font-weight: 800;
        padding: 4px 14px; border-radius: 99px;
      }
      .sq-rank-1 .sq-rank-badge { background: var(--gold-500, #f5a623); color: var(--navy-900); }
      .sq-result-card-head { display: flex; align-items: center; gap: 10px; margin: 10px 0 12px; }
      .sq-result-icon { font-size: 26px; }
      .sq-result-name { font-size: 17px; font-weight: 800; color: var(--navy-900); }
      .sq-result-comment {
        display: flex; align-items: flex-start; gap: 10px;
        background: var(--ink-50, #f8f9fa); border-radius: 10px; padding: 10px 12px;
        margin-bottom: 14px;
      }
      .sq-result-comment p { margin: 4px 0 0; font-size: 13px; line-height: 1.6; color: var(--navy-800); }
      .sq-start-btn { width: 100%; padding: 12px; font-size: 14px; border-radius: 10px; }

      .sq-result-btns {
        display: flex; flex-direction: column; gap: 10px;
        width: 100%; max-width: 400px; margin-top: 10px;
      }
      .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); }
      .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){
        .sq-wrap { padding: 0 12px 100px; }
        .sq-header { padding: 14px 0 12px; }
        .sq-question { padding: 16px 16px; }
        .sq-q-text { font-size: 15px; }
        .sq-option { padding: 12px 14px; font-size: 14px; }
        .sq-mascot-bubble { font-size: 13px; padding: 12px 14px; }
        .sq-result-title { font-size: 19px; }
        .sq-result-btns { max-width: 100%; }
      }
      @media(max-width:480px){
        .sq-wrap { padding: 0 10px 100px; }
        .sq-question { padding: 14px 12px; }
        .sq-q-text { font-size: 14px; }
        .sq-option { padding: 10px 12px; font-size: 13px; gap: 10px; }
        .sq-result-name { font-size: 15px; }
      }
    `}</style>
  );
}

window.StyleQuizPage = StyleQuizPage;
