/* レッスンコンテンツページ */

// マークダウンを HTML に変換し、会話バブル・figbox を後処理する
function renderArticle(markdown) {
  if (!markdown) return "";

  // marked でレンダリング
  let html = marked.parse(markdown);

  // 💬 株次郎: ... → kabu バブル
  html = html.replace(
    /<p>💬\s*(株次郎|カブ次郎)[：:]\s*([\s\S]*?)<\/p>/g,
    (_, _name, body) =>
      `<div class="conv-kabu"><div class="conv-avatar conv-avatar--kabu"></div><div class="conv-body">${body.trim()}</div></div>`
  );

  // 🎓 生徒: ... → student バブル
  html = html.replace(
    /<p>🎓\s*(生徒|生徒さん|あなた)[：:]\s*([\s\S]*?)<\/p>/g,
    (_, _name, body) =>
      `<div class="conv-student"><div class="conv-body">${body.trim()}</div><div class="conv-avatar conv-avatar--stu"></div></div>`
  );

  // 📊 ... → figbox
  html = html.replace(
    /<p>📊([^<]*)<\/p>/g,
    (_, body) =>
      `<div class="figbox"><span class="figbox-icon">📊</span><span>${body.trim()}</span></div>`
  );

  // 💡 ... → tip box
  html = html.replace(
    /<p>💡([^<]*)<\/p>/g,
    (_, body) =>
      `<div class="tipbox"><span class="tipbox-icon">💡</span><span>${body.trim()}</span></div>`
  );

  return html;
}

function Lesson({ nav, progress, lessonSlug, chapterId, completeLesson }) {
  const chapters    = window.APP_DATA.chapters;
  const lessonStore = window.APP_DATA.lessons;
  const completed   = progress.completed;
  const membershipStatus = progress.membershipStatus || 'free';

  const detail = lessonStore[lessonSlug];
  if (!detail) return <div className="lesson-wrap"><p>レッスンが見つかりません</p></div>;

  const isPaid = detail.access === 'paid';

  // クライアント側の順番ロック判定（無料レッスンに即適用、有料はサーバーが真実の源）
  const isStepLocked = !isSlugUnlocked(lessonSlug, progress);

  // 有料コンテンツのフェッチ状態（paid 専用）
  // "idle" | "loading" | "ready" | "locked" | "step-locked" | "error"
  const [paidPhase, setPaidPhase] = React.useState("idle");
  const [fetchedArticle, setFetchedArticle] = React.useState(null);

  // lessonSlug が変わるたびに記事を取得（無料は不要、有料はAPI）
  React.useEffect(function() {
    if (!isPaid) { setFetchedArticle(null); setPaidPhase("idle"); return; }
    // セッション内キャッシュ（APP_DATA へ書き戻し済みの場合）
    if (detail.article) {
      setFetchedArticle(detail.article);
      setPaidPhase("ready");
      return;
    }
    setPaidPhase("loading");
    fetch('/api/lesson/' + lessonSlug)
      .then(function(r) {
        if (r.status === 403) {
          return r.json().then(function(body) {
            setPaidPhase(body && body.error === 'paid_required' ? "locked" : "step-locked");
            return null;
          }).catch(function() { setPaidPhase("locked"); return null; });
        }
        if (!r.ok) { setPaidPhase("error"); return null; }
        return r.json();
      })
      .then(function(data) {
        if (!data) return;
        // APP_DATA に書き戻してセッション内再訪時の再フェッチを防ぐ
        if (window.APP_DATA && window.APP_DATA.lessons && window.APP_DATA.lessons[lessonSlug]) {
          window.APP_DATA.lessons[lessonSlug].article = data.article;
          window.APP_DATA.lessons[lessonSlug].quiz    = data.quiz || [];
        }
        setFetchedArticle(data.article);
        setPaidPhase("ready");
      })
      .catch(function() { setPaidPhase("error"); });
  }, [lessonSlug]);

  // 最終的な表示フェーズ（無料はクライアント判定、有料はサーバー判定）
  const articlePhase = !isPaid
    ? (isStepLocked ? "step-locked" : "ready")
    : paidPhase;

  // 同じチャプター内の前後レッスンを計算
  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 prevLesson = curIdx > 0 ? chLessons[curIdx - 1] : null;
  const nextLesson = curIdx < chLessons.length - 1 ? chLessons[curIdx + 1] : null;

  // hasQuiz: 有料レッスンは quiz=[] になるため hasQuiz フラグで判定
  const hasQuiz = !!(detail.hasQuiz || (detail.quiz && detail.quiz.length > 0));
  const isComprehensiveTest = /総合テスト|総まとめ/.test(detail.title || "");

  // 本文（ready になってから計算）
  const articleFull = articlePhase === "ready"
    ? (fetchedArticle || detail.article || "")
    : "";
  const quizMarker  = articleFull.indexOf("## 📝 ミニテスト");
  const articleBody = quizMarker >= 0 ? articleFull.slice(0, quizMarker) : articleFull;
  const htmlContent = renderArticle(articleBody);

  const handleComplete = function() { completeLesson(lessonSlug); };

  return (
    <div className="lesson-wrap">
      <LessonStyles />

      {/* ── サイドバー（カリキュラムリスト） ── */}
      <aside className="lesson-sidebar">
        <button className="lesson-back-btn" onClick={function() { nav.goBack(); }}>
          ← チャプターへ
        </button>

        {ch && (
          <>
            <div className="lesson-sidebar-chap">
              <span>{ch.icon}</span> {ch.title}
            </div>
            <nav className="lesson-nav-list">
              {chLessons.map(function(l, i) {
                const lCleared    = isLessonCleared(l.slug, lessonStore, progress);
                const lAccessible = isLessonAccessible(i, chLessons, lessonStore, progress);
                const lActive     = l.slug === lessonSlug;
                const lMemberLock = l.access === 'paid' && membershipStatus !== 'active';
                return (
                  <button
                    key={l.slug}
                    className={`lesson-nav-item ${lActive ? "active" : ""} ${lCleared ? "done" : ""} ${!lAccessible ? "locked" : ""}`}
                    onClick={function() { lAccessible && nav.goLesson(l.slug, chapterId); }}
                    disabled={!lAccessible}
                    title={!lAccessible ? "前のセクターをクリアしてから進もう" : ""}
                  >
                    <span className="lesson-nav-num">
                      {lCleared ? "✓" : (!lAccessible || lMemberLock) ? "🔒" : i + 1}
                    </span>
                    <span className="lesson-nav-title">{l.title}</span>
                  </button>
                );
              })}
            </nav>
          </>
        )}
      </aside>

      {/* ── メインコンテンツ ── */}
      <main className="lesson-main">
        {/* ヘッダー */}
        <div className="lesson-header">
          <div className="lesson-header-meta">
            {detail.isFree && <span className="tag tag-free">無料</span>}
            {!detail.isFree && <span className="tag tag-paid">有料</span>}
            {ch && <span className="lesson-chap-label">{ch.title} › セクター {curIdx + 1}</span>}
          </div>
          <h1 className="lesson-title">{detail.title}</h1>
          <p className="lesson-subtitle">{detail.subtitle}</p>
        </div>

        {/* セクターイラスト（存在する場合のみ） */}
        {detail.illustration && (
          <div className="lesson-illustration">
            <img src={detail.illustration} alt={detail.title} className="lesson-illustration-img" />
          </div>
        )}

        {/* ── 有料コンテンツ：ローディング ── */}
        {isPaid && articlePhase === "loading" && (
          <div className="lesson-loading">
            <Mascot size={64} mood="happy" />
            <p className="lesson-loading-txt">コンテンツを読み込み中…</p>
          </div>
        )}

        {/* ── 有料コンテンツ：アップグレード案内（403・未購入） ── */}
        {isPaid && articlePhase === "locked" && (
          <div className="lesson-upgrade-cta">
            <div className="luc-lock">🔒</div>
            <h3 className="luc-title">有料プランのコンテンツです</h3>
            <p className="luc-desc">
              このセクターは有料会員限定です。<br />
              プランに加入すると応用コース全セクターにアクセスできます。
            </p>
            <div className="luc-actions">
              <button className="btn btn-primary luc-btn" disabled style={{ opacity: 0.55, cursor: "not-allowed" }}>
                近日公開予定 — プランをアップグレード
              </button>
              <button className="btn luc-back" onClick={function() { nav.goBack(); }}>
                ← チャプターへ戻る
              </button>
            </div>
          </div>
        )}

        {/* ── 順番ロック（前のセクター未クリア） ── */}
        {articlePhase === "step-locked" && (
          <div className="lesson-step-locked">
            <div className="lsl-icon">🔒</div>
            <h3 className="lsl-title">
              {(ch?.courseType === 'applied' && curIdx === 0)
                ? "基礎コース修了後に解放されます"
                : "前のセクターをクリアすると解放されます"}
            </h3>
            <p className="lsl-desc">
              {(ch?.courseType === 'applied' && curIdx === 0)
                ? "基礎コース（はじめに〜スタイル）のすべてのセクターをクリアすると、応用コース全体が解放されます。"
                : "前のセクターのミニテストに合格（またはセクターを完了）してから進みましょう。"}
            </p>
            <button className="btn luc-back" onClick={function() { nav.goBack(); }}>
              ← チャプターへ戻る
            </button>
          </div>
        )}

        {/* ── 有料コンテンツ：通信エラー ── */}
        {isPaid && articlePhase === "error" && (
          <div className="lesson-fetch-error">
            <p>コンテンツの読み込みに失敗しました。</p>
            <button className="btn luc-back" onClick={function() { window.location.reload(); }}>
              ページを再読み込み
            </button>
          </div>
        )}

        {/* ── 記事本文（free / paid+ready） ── */}
        {articlePhase === "ready" && (
          <>
            {/* マスコット + 吹き出し */}
            <div className="lesson-kabu-intro">
              <Mascot size={64} mood="happy" />
              <div className="lesson-kabu-bubble">
                このセクターで学ぶこと、一緒に確認しましょう！わからないことがあれば何度でも読み返してみてください📖
              </div>
            </div>

            {/* 記事本文 */}
            <div
              className="lesson-article"
              dangerouslySetInnerHTML={{ __html: htmlContent }}
            />

            {/* フッターアクション（本文取得済みのときのみ表示） */}
            <div className="lesson-footer">
              {hasQuiz ? (
                isLessonCleared(lessonSlug, lessonStore, progress) ? (
                  <div className="lesson-done-badge">✅ 合格済み・完了</div>
                ) : (
                  <div className="lesson-quiz-notice">
                    {isComprehensiveTest
                      ? "📝 この総合テストに合格すると完了になります"
                      : "📝 このセクターはミニテストに合格すると完了になります"}
                  </div>
                )
              ) : (
                completed.includes(lessonSlug) ? (
                  <div className="lesson-done-badge">✅ 完了済み</div>
                ) : (
                  <button className="btn btn-primary lesson-done-btn" onClick={handleComplete}>
                    ✓ このセクターを完了にする
                  </button>
                )
              )}

              {hasQuiz && (
                <button
                  className="btn btn-gold lesson-quiz-btn"
                  onClick={function() { nav.goQuiz(lessonSlug); }}
                >
                  {isComprehensiveTest ? "📝 総合テストを始める" : "📝 ミニテストへ進む"}
                </button>
              )}
            </div>
          </>
        )}

        {/* 前後ナビ */}
        <div className="lesson-pager">
          {prevLesson ? (
            <button className="lesson-pager-btn" onClick={function() { nav.goLesson(prevLesson.slug, chapterId); }}>
              ← {prevLesson.title}
            </button>
          ) : <div />}
          {nextLesson && (
            <button className="lesson-pager-btn next" onClick={function() { nav.goLesson(nextLesson.slug, chapterId); }}>
              {nextLesson.title} →
            </button>
          )}
        </div>
      </main>
    </div>
  );
}

function LessonStyles() {
  return (
    <style>{`
      .lesson-wrap {
        display: grid;
        grid-template-columns: 260px 1fr;
        min-height: 100vh;
        background: var(--ink-50, #f8f9fa);
      }

      /* ── サイドバー ── */
      .lesson-sidebar {
        background: var(--navy-900);
        color: white;
        padding: 24px 16px;
        display: flex;
        flex-direction: column;
        gap: 12px;
        position: sticky;
        top: 0;
        height: 100vh;
        overflow-y: auto;
      }
      .lesson-back-btn {
        background: rgba(255,255,255,.1); border: none; color: rgba(255,255,255,.8);
        padding: 8px 12px; border-radius: 8px; font-size: 12px; cursor: pointer;
        text-align: left; width: 100%;
      }
      .lesson-back-btn:hover { background: rgba(255,255,255,.18); }
      .lesson-sidebar-chap {
        font-size: 12px; font-weight: 700; text-transform: uppercase;
        letter-spacing: .06em; color: var(--gold-400); padding: 8px 0 4px;
        border-top: 1px solid rgba(255,255,255,.12);
      }
      .lesson-nav-list { display: flex; flex-direction: column; gap: 2px; }
      .lesson-nav-item {
        display: flex; align-items: flex-start; gap: 10px;
        background: none; border: none; color: rgba(255,255,255,.65);
        padding: 8px 10px; border-radius: 8px; cursor: pointer; text-align: left;
        font-size: 12px; transition: background .12s;
      }
      .lesson-nav-item:hover { background: rgba(255,255,255,.08); color: white; }
      .lesson-nav-item.active { background: rgba(255,255,255,.15); color: white; }
      .lesson-nav-item.done { color: var(--green-400, #4ade80); }
      .lesson-nav-num {
        width: 20px; height: 20px; border-radius: 50%; background: rgba(255,255,255,.15);
        display: flex; align-items: center; justify-content: center;
        font-size: 10px; font-weight: 700; flex-shrink: 0;
      }
      .lesson-nav-item.active .lesson-nav-num { background: var(--gold-400); color: var(--navy-900); }
      .lesson-nav-item.done .lesson-nav-num  { background: var(--green-500, #22c55e); color: white; }
      .lesson-nav-title { line-height: 1.4; }

      /* ── メイン ── */
      .lesson-main { padding: 40px 48px; max-width: 800px; }

      .lesson-header { margin-bottom: 28px; }
      .lesson-header-meta { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; }
      .lesson-chap-label { font-size: 12px; color: var(--ink-400); }
      .lesson-title { font-size: 30px; font-weight: 800; color: var(--navy-900); margin: 0 0 6px; line-height: 1.3; }
      .lesson-subtitle { font-size: 15px; color: var(--ink-500); margin: 0; }

      /* ローディング */
      .lesson-loading {
        display: flex; flex-direction: column; align-items: center; gap: 16px;
        padding: 60px 20px; text-align: center;
      }
      .lesson-loading-txt { font-size: 15px; color: var(--ink-400); }

      /* 順番ロック */
      .lesson-step-locked {
        display: flex; flex-direction: column; align-items: center; gap: 16px;
        text-align: center; padding: 48px 24px;
        background: var(--ink-50, #f8f9fa);
        border: 2px solid var(--ink-200);
        border-radius: 16px; margin-bottom: 32px;
      }
      .lsl-icon { font-size: 40px; }
      .lsl-title { font-size: 18px; font-weight: 800; color: var(--navy-900); margin: 0; }
      .lsl-desc { font-size: 14px; color: var(--ink-500); line-height: 1.7; margin: 0; max-width: 360px; }

      /* アップグレードCTA */
      .lesson-upgrade-cta {
        display: flex; flex-direction: column; align-items: center; gap: 16px;
        text-align: center; padding: 48px 24px;
        background: var(--gold-50, #fffbeb);
        border: 2px solid var(--gold-300, #fcd34d);
        border-radius: 16px; margin-bottom: 32px;
      }
      .luc-lock { font-size: 48px; }
      .luc-title { font-size: 20px; font-weight: 800; color: var(--navy-900); margin: 0; }
      .luc-desc { font-size: 14px; color: var(--ink-600); line-height: 1.7; margin: 0; }
      .luc-actions { display: flex; flex-direction: column; align-items: center; gap: 12px; width: 100%; max-width: 320px; }
      .luc-btn { padding: 14px 32px; font-size: 15px; width: 100%; border-radius: 99px; }
      .luc-back {
        background: white; color: var(--navy-800);
        border: 2px solid var(--navy-200); border-radius: 99px;
        padding: 10px 24px; font-weight: 600; font-size: 14px; cursor: pointer;
        transition: background .15s;
      }
      .luc-back:hover { background: var(--navy-50); }

      /* 通信エラー */
      .lesson-fetch-error {
        display: flex; flex-direction: column; align-items: center; gap: 12px;
        padding: 40px 20px; text-align: center;
      }
      .lesson-fetch-error p { font-size: 15px; color: var(--ink-500); }

      /* マスコット導入 */
      .lesson-kabu-intro {
        display: flex; align-items: flex-start; gap: 14px;
        background: var(--navy-50, #eef2ff); border-radius: 14px;
        padding: 18px 20px; margin-bottom: 32px;
      }
      .lesson-kabu-bubble {
        background: white; border-radius: 10px; padding: 12px 16px;
        font-size: 14px; line-height: 1.65; color: var(--navy-800);
        box-shadow: 0 1px 4px rgba(0,0,0,.07);
        position: relative; flex: 1;
      }
      .lesson-kabu-bubble::before {
        content: ""; position: absolute; left: -8px; top: 16px;
        border: 8px solid transparent; border-right-color: white;
        border-left: none;
      }

      /* 記事本文 */
      .lesson-article {
        font-size: 15px; line-height: 1.85; color: var(--ink-700);
        margin-bottom: 40px;
      }
      /* ── 記事内画像（SBI証券スクショ等）── */
      .lesson-article img {
        display: block;
        max-width: 400px;   /* PC: 縦長スクショは400px上限 */
        width: 100%;
        height: auto;
        margin: 16px auto;
        border-radius: 12px;
        border: 1px solid var(--ink-100);
        box-shadow: 0 4px 16px rgba(0,0,0,.12);
      }
      /* SVGチャート（横長データ図解）は幅を広く取る */
      .lesson-article img[src$=".svg"] {
        max-width: 640px;
      }
      .lesson-article h1, .lesson-article h2 {
        font-size: 20px; font-weight: 800; color: var(--navy-900);
        margin: 36px 0 14px; padding-bottom: 8px;
        border-bottom: 2px solid var(--navy-100);
      }
      .lesson-article h3 {
        font-size: 16px; font-weight: 700; color: var(--navy-800); margin: 28px 0 10px;
      }
      .lesson-article p { margin: 0 0 16px; }
      .lesson-article ul, .lesson-article ol { padding-left: 20px; margin: 0 0 16px; }
      .lesson-article li { margin-bottom: 6px; }
      .lesson-article strong { color: var(--navy-900); font-weight: 700; }
      .lesson-article blockquote {
        border-left: 4px solid var(--gold-400); margin: 20px 0;
        padding: 12px 20px; background: var(--gold-50, #fffbeb); border-radius: 0 8px 8px 0;
        color: var(--navy-800);
      }
      .lesson-article table {
        width: 100%; border-collapse: collapse; margin: 20px 0; font-size: 14px;
      }
      .lesson-article th {
        background: var(--navy-900); color: white; padding: 10px 14px; text-align: left;
      }
      .lesson-article td { padding: 9px 14px; border-bottom: 1px solid var(--navy-100); }
      .lesson-article tr:nth-child(even) td { background: var(--navy-50, #f5f7ff); }
      .lesson-article code {
        background: var(--ink-100); padding: 2px 6px; border-radius: 4px;
        font-family: monospace; font-size: 13px;
      }
      .lesson-article pre { background: var(--ink-100); padding: 16px; border-radius: 8px; overflow-x: auto; }
      .lesson-article pre code { background: none; padding: 0; }
      .lesson-article hr { border: none; border-top: 1px solid var(--ink-200); margin: 28px 0; }

      /* セクターイラスト */
      .lesson-illustration {
        text-align: center;
        margin: 0 0 28px;
      }
      .lesson-illustration-img {
        max-width: 280px;
        width: 100%;
        height: auto;
        border-radius: 16px;
        border: 1px solid var(--ink-100);
        box-shadow: 0 2px 12px rgba(0,0,0,.06);
        display: block;
        margin: 0 auto;
      }

      /* 会話バブル */
      .conv-kabu {
        display: flex; align-items: flex-start; gap: 12px;
        margin: 20px 0; background: var(--navy-50, #eef2ff);
        border-radius: 12px; padding: 14px 16px;
      }
      .conv-student {
        display: flex; align-items: flex-start; gap: 12px;
        margin: 20px 0; background: var(--ink-50, #f8f9fa);
        border-radius: 12px; padding: 14px 16px; flex-direction: row-reverse;
      }
      .conv-avatar {
        width: 44px; height: 44px; border-radius: 50%;
        flex-shrink: 0;
        background-size: cover;
        background-position: center center;
        background-repeat: no-repeat;
        background-color: var(--navy-100);
      }
      .conv-avatar--kabu {
        background-image: url("assets/kabujiro_mainicon.jpg");
      }
      .conv-avatar--stu {
        background-image: url("assets/student_aicon.jpg");
        background-color: var(--green-100, #dcfce7);
      }
      .conv-body { font-size: 14px; line-height: 1.65; color: var(--navy-800); flex: 1; }

      /* figbox */
      .figbox {
        display: flex; align-items: flex-start; gap: 10px;
        background: white; border: 2px solid var(--navy-200);
        border-radius: 10px; padding: 14px 16px; margin: 20px 0;
        font-size: 14px; color: var(--navy-800);
      }
      .figbox-icon { font-size: 18px; flex-shrink: 0; }

      /* tipbox */
      .tipbox {
        display: flex; align-items: flex-start; gap: 10px;
        background: var(--gold-50, #fffbeb); border: 2px solid var(--gold-300);
        border-radius: 10px; padding: 14px 16px; margin: 20px 0;
        font-size: 14px; color: var(--navy-800);
      }
      .tipbox-icon { font-size: 18px; flex-shrink: 0; }

      /* フッター */
      .lesson-footer {
        display: flex; align-items: center; gap: 14px; margin-bottom: 32px;
        padding: 20px 0; border-top: 1px solid var(--ink-200);
      }
      .lesson-done-btn { padding: 12px 28px; font-size: 15px; }
      .lesson-done-badge { font-size: 15px; font-weight: 700; color: var(--green-600, #16a34a); }
      .lesson-quiz-notice {
        font-size: 14px; color: var(--navy-700);
        background: var(--navy-50); border-radius: 8px;
        padding: 10px 16px; border-left: 4px solid var(--gold-400);
      }
      .lesson-quiz-btn { padding: 12px 28px; font-size: 15px; }
      .lesson-nav-item.locked { opacity: .45; cursor: not-allowed; }
      .lesson-nav-item:disabled { cursor: not-allowed; }

      .btn-gold {
        background: var(--gold-500, #eab308); color: white; border: none;
        border-radius: 99px; font-weight: 700; cursor: pointer;
        transition: background .15s;
      }
      .btn-gold:hover { background: var(--gold-600, #ca8a04); }

      /* ページネーション */
      .lesson-pager {
        display: flex; justify-content: space-between; gap: 12px; padding-bottom: 48px;
      }
      .lesson-pager-btn {
        padding: 10px 20px; border-radius: 99px; border: 2px solid var(--navy-200);
        background: white; color: var(--navy-800); font-size: 13px; font-weight: 600;
        cursor: pointer; max-width: 45%; white-space: nowrap; overflow: hidden;
        text-overflow: ellipsis;
      }
      .lesson-pager-btn:hover { background: var(--navy-50); }
      .lesson-pager-btn.next { margin-left: auto; }

      @media(max-width:768px){
        .lesson-wrap {
          grid-template-columns: 1fr;
          overflow-x: hidden; /* preブロック等が親を押し広げるのを防止 */
        }
        .lesson-sidebar { display: none; }
        /* width: 100% + overflow: hidden で見切れを根本解決 */
        .lesson-main {
          padding: 20px 16px 100px;
          max-width: 100%;
          width: 100%;
          overflow-x: hidden;
          box-sizing: border-box;
        }
        /* テキスト折り返し強制 */
        .lesson-title {
          font-size: 22px;
          word-break: break-word;
          overflow-wrap: break-word;
        }
        .lesson-header-meta { flex-wrap: wrap; }
        .lesson-chap-label { white-space: normal; word-break: break-word; }
        /* 記事本文の全要素 */
        .lesson-article {
          font-size: 14px;
          word-break: break-word;
          overflow-wrap: break-word;
        }
        .lesson-article h1, .lesson-article h2 {
          font-size: 17px; margin: 24px 0 10px;
          word-break: break-word; overflow-wrap: break-word;
        }
        .lesson-article h3 {
          font-size: 15px;
          word-break: break-word; overflow-wrap: break-word;
        }
        /* テーブルは横スクロール許可 */
        .lesson-article table { display: block; overflow-x: auto; }
        /* 会話バブル: min-width:0 でflex子要素のはみ出し防止 */
        .conv-kabu, .conv-student {
          padding: 12px 12px;
          overflow: hidden;
        }
        .conv-kabu .conv-body, .conv-student .conv-body {
          min-width: 0;
          word-break: break-word;
          overflow-wrap: break-word;
        }
        .conv-avatar { width: 36px; height: 36px; }
        /* マスコット導入バブル */
        .lesson-kabu-intro { padding: 14px 14px; gap: 10px; overflow: hidden; }
        .lesson-kabu-bubble {
          font-size: 13px;
          min-width: 0;
          word-break: break-word;
          overflow-wrap: break-word;
        }
        .lesson-illustration-img { max-width: 220px; }
        .lesson-article img { max-width: 100%; }   /* モバイル: 画面幅いっぱいまで */
        .lesson-article img[src$=".svg"] { max-width: 100%; }
        .lesson-pager { padding-bottom: 16px; }
        .lesson-pager-btn { max-width: 48%; font-size: 12px; padding: 8px 14px; }
        .lesson-quiz-notice { word-break: break-word; }
        .figbox, .tipbox { overflow: hidden; word-break: break-word; overflow-wrap: break-word; }
        /* preブロック: 横スクロール可 + 最大幅制限 */
        .lesson-article pre {
          max-width: 100%;
          overflow-x: auto;
          white-space: pre;          /* 折り返しなし＋横スクロールで可読性維持 */
          -webkit-overflow-scrolling: touch;
        }
        /* 注意書き・キャプション等の長テキスト */
        .lesson-article p,
        .lesson-article li,
        .image-caption {
          word-break: break-word;
          overflow-wrap: break-word;
        }
      }
      @media(max-width:480px){
        .lesson-main { padding: 16px 12px 100px; }
        .lesson-title { font-size: 19px; }
      }
    `}</style>
  );
}

window.Lesson = Lesson;
