/* =========================================================
   英文解釈ラボ — app  (React, mounts #app)
   ========================================================= */
const { useState, useMemo } = React;
const K = window.KAISHAKU;
const R = K.roles;

/* ---------- shared bits ---------- */

function RoleChip({ role, sub, big }) {
  const m = R[role];
  return (
    <span className="role-chip" style={{
      color: '#fff', background: m.color,
      fontSize: big ? 13 : 11, padding: big ? '.2em .7em' : '.14em .55em',
    }}>
      {m.key}{sub ? <span style={{opacity:.85, fontWeight:700}}>·{sub}</span> : null}
      <span style={{fontFamily:'var(--jp)', fontWeight:700, opacity:.92}}>{m.jp}</span>
    </span>
  );
}

function Legend() {
  return (
    <div className="legend">
      {Object.values(R).map(m => (
        <span className="legend-item" key={m.key}>
          <span className="legend-dot" style={{ background: m.color }}>{m.key}</span>
          <span className="legend-jp">{m.jp}</span>
        </span>
      ))}
    </div>
  );
}

function TypeBadge({ s }) {
  return (
    <span className="type-badge">
      <b>{s.typeJp}</b>
      <span className="type-formula">{s.type.split('').join(' ')}</span>
    </span>
  );
}

/* ---------- INTERACTIVE ---------- */

function Interactive() {
  const [si, setSi] = useState(0);
  const [show, setShow] = useState(false);
  const [sel, setSel] = useState(null);
  const [trans, setTrans] = useState(false);
  const s = K.sentences[si];

  function pick(i) { setSi(i); setSel(null); setShow(false); setTrans(false); }

  const active = sel != null ? s.chunks[sel] : null;

  return (
    <div className="mode">
      <div className="mode-intro">
        <h2>語句を<span className="mark">クリック</span>して、文の骨格を体感する。</h2>
        <p>英文をタップすると、それぞれの語句が文の中で果たす<b>役割（SVOC）</b>と訳が浮かび上がります。「構造を表示」で全体の設計図を一気に確認。</p>
      </div>

      <div className="sentence-nav">
        {K.sentences.map((x, i) => (
          <button key={x.id} className={'snav' + (i === si ? ' on' : '')} onClick={() => pick(i)}>
            {x.type}
          </button>
        ))}
      </div>

      <div className="card stage">
        <div className="stage-top">
          <TypeBadge s={s} />
          <div className="stage-meta">
            <span className="pill-meta">{s.level}</span>
            <span className="pill-meta">{s.theme}</span>
          </div>
        </div>

        <div className={'sentence' + (show ? ' show-structure' : '')}>
          {s.chunks.map((c, i) => {
            const m = R[c.role];
            const on = sel === i;
            const reveal = show || on;
            return (
              <button
                key={i}
                className={'chunk' + (on ? ' sel' : '')}
                onClick={() => setSel(on ? null : i)}
                style={reveal ? {
                  background: m.bg,
                  boxShadow: `inset 0 -3px 0 ${m.color}`,
                  color: '#3a2a1c',
                } : {}}
              >
                <span className="chunk-tag" style={{ opacity: show ? 1 : 0 }}>
                  <span className="ctag" style={{ background: m.color }}>{m.key}{c.sub ? '·'+c.sub : ''}</span>
                </span>
                <span className="chunk-text">{c.text}</span>
              </button>
            );
          })}
        </div>

        <div className="stage-tools">
          <button className={'toggle' + (show ? ' on' : '')} onClick={() => setShow(!show)}>
            {show ? '構造を隠す' : '構造を表示'}
          </button>
          <button className={'toggle' + (trans ? ' on' : '')} onClick={() => setTrans(!trans)}>
            {trans ? '全訳を隠す' : '全訳を表示'}
          </button>
          <Legend />
        </div>

        {trans && <div className="full-trans">{s.jp}</div>}
      </div>

      <div className={'detail' + (active ? ' filled' : '')}>
        {active ? (
          <React.Fragment>
            <div className="detail-head">
              <RoleChip role={active.role} sub={active.sub} big />
              <span className="detail-en">{active.text}</span>
            </div>
            <div className="detail-jp">{active.jp}</div>
            <p className="detail-note">{active.note}</p>
          </React.Fragment>
        ) : (
          <div className="detail-hint">語句をクリックすると、役割・訳・解説が表示されます。</div>
        )}
      </div>

      <div className="point-box">
        <span className="point-label">読解のコツ</span>
        <p>{s.point}</p>
      </div>
    </div>
  );
}

/* ---------- ARTICLE ---------- */

function Article() {
  const [si, setSi] = useState(0);
  const s = K.sentences[si];
  return (
    <div className="mode">
      <div className="mode-intro">
        <h2>例文を<span className="mark">構造で色分け</span>して、一文を分解する。</h2>
        <p>骨格(SVOC)を色で示し、語句ごとに「訳」と「文法の理由」を順に読み解く記事形式。じっくり腰を据えて理解したい人へ。</p>
      </div>

      <div className="sentence-nav">
        {K.sentences.map((x, i) => (
          <button key={x.id} className={'snav' + (i === si ? ' on' : '')} onClick={() => setSi(i)}>
            {x.type}
          </button>
        ))}
      </div>

      <article className="card article">
        <div className="stage-top">
          <TypeBadge s={s} />
          <div className="stage-meta">
            <span className="pill-meta">{s.level}</span>
            <span className="pill-meta">{s.theme}</span>
          </div>
        </div>

        <div className="sentence show-structure article-sentence">
          {s.chunks.map((c, i) => {
            const m = R[c.role];
            return (
              <span className="chunk static" key={i}
                style={{ background: m.bg, boxShadow: `inset 0 -3px 0 ${m.color}`, color: '#3a2a1c' }}>
                <span className="chunk-tag"><span className="ctag" style={{ background: m.color }}>{m.key}{c.sub?'·'+c.sub:''}</span></span>
                <span className="chunk-text">{c.text}</span>
              </span>
            );
          })}
        </div>

        <Legend />

        <div className="full-trans solid">{s.jp}</div>

        <div className="breakdown">
          <div className="breakdown-title">語句ごとの読み解き</div>
          {s.chunks.map((c, i) => (
            <div className="bd-row" key={i}>
              <div className="bd-chip"><RoleChip role={c.role} sub={c.sub} /></div>
              <div className="bd-body">
                <div className="bd-en">{c.text} <span className="bd-jp">— {c.jp}</span></div>
                <p className="bd-note">{c.note}</p>
              </div>
            </div>
          ))}
        </div>

        <div className="point-box">
          <span className="point-label">読解のコツ</span>
          <p>{s.point}</p>
        </div>
      </article>
    </div>
  );
}

/* ---------- QUIZ ---------- */

function Quiz() {
  const [qi, setQi] = useState(0);
  const [ans, setAns] = useState(null);
  const q = K.quizzes[qi];
  const answered = ans != null;

  function choose(id) { if (!answered) setAns(id); }
  function next() { setQi((qi + 1) % K.quizzes.length); setAns(null); }
  function reset() { setAns(null); }

  return (
    <div className="mode">
      <div className="mode-intro">
        <h2>なぜ<span className="mark">「その選択肢」</span>が正解か？</h2>
        <p>複雑に見える問題も、文の型と品詞の役割で仕分ければ、正解の根拠が明確になります。選んでから理由を確認しましょう。</p>
      </div>

      <div className="quiz-progress">
        {K.quizzes.map((_, i) => (
          <span key={i} className={'qdot' + (i === qi ? ' on' : '')} />
        ))}
        <span className="qcount">Q{qi + 1} / {K.quizzes.length}</span>
      </div>

      <div className="card quiz">
        <div className="quiz-stem">
          {q.stemBefore && <span>{q.stemBefore} </span>}
          <span className="blank">{answered ? K.quizzes[qi].choices.find(c=>c.correct).word : '_____'}</span>
          <span> {q.stemAfter}</span>
        </div>
        <div className="quiz-prompt">
          <span className="q-mark">Q.</span>{q.prompt}
          <span className="q-hint">{q.typeHint}</span>
        </div>

        <div className="choices">
          {q.choices.map(c => {
            let cls = 'choice';
            if (answered) {
              if (c.correct) cls += ' correct';
              else if (c.id === ans) cls += ' wrong';
              else cls += ' dim';
            }
            return (
              <button key={c.id} className={cls} onClick={() => choose(c.id)} disabled={answered}>
                <span className="ch-key">{c.id}</span>
                <span className="ch-main">
                  <span className="ch-word">{c.word}
                    {answered && c.correct && <span className="ch-check"> ✓</span>}
                  </span>
                  {answered && <span className="ch-why">{c.why}</span>}
                </span>
                <span className="ch-pos">{c.pos}</span>
              </button>
            );
          })}
        </div>

        {answered && (
          <div className="quiz-explain">
            <span className="point-label">解説</span>
            <p>{q.explain}</p>
            <div className="quiz-actions">
              <button className="btn btn-ghost" onClick={reset}>もう一度</button>
              <button className="btn btn-primary" onClick={next}>次の問題へ →</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

/* ---------- APP ---------- */

const MODES = [
  { key: 'interactive', label: 'インタラクティブ', sub: 'クリックで構造を体感' },
  { key: 'article',     label: '記事型',           sub: '色分けで一文を分解' },
  { key: 'quiz',        label: 'クイズ型',         sub: '4択で根拠を確認' },
];

function App() {
  const [mode, setMode] = useState('interactive');
  return (
    <div className="wrap">
      <div dangerouslySetInnerHTML={{ __html: window.SITE.headerHtml() + window.SITE.navHtml('lab') }} />

      <section className="hero-lab">
        <div className="hero-lab-inner">
          <p className="kicker">英文解釈ラボ</p>
          <h1>英語は「単語」ではなく<br /><span className="mark-line">「構造」</span>で読む。</h1>
          <p className="lede">文の型(5文型)と品詞の役割が見えれば、長い一文もパズルのように明快になる。3つのモードで、構造で読む力を鍛えるトレーニングページです。</p>
        </div>
      </section>

      <div className="mode-tabs" role="tablist">
        {MODES.map(m => (
          <button key={m.key} role="tab" aria-selected={mode === m.key}
            className={'mtab' + (mode === m.key ? ' on' : '')} onClick={() => setMode(m.key)}>
            <span className="mtab-label">{m.label}</span>
            <span className="mtab-sub">{m.sub}</span>
          </button>
        ))}
      </div>

      <main className="content">
        {mode === 'interactive' && <Interactive />}
        {mode === 'article' && <Article />}
        {mode === 'quiz' && <Quiz />}
      </main>

      <section className="cta-band">
        <div className="cta-inner">
          <p className="cta-kick">TOEIC Business Training</p>
          <h2>「読み流す」から卒業し、<br />理詰めで解く快感を。</h2>
          <a className="btn btn-cta" href="plan.html">
            <span className="cta-pill">🔗 無料トライアルはこちら</span>
          </a>
          <p className="cta-url">biz-toeic990.com</p>
        </div>
      </section>

      <footer className="site-foot">
        <span>© TOEIC Business Training</span>
        <a href="about.html">サービス紹介 →</a>
      </footer>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('app')).render(<App />);
