/* チャプター詳細ページ */

function ChapterDetail({ nav, progress, chapterId, completeLesson }) {
  const chapters = window.APP_DATA.chapters;
  const lessonDetails = window.APP_DATA.lessons;
  const ch = chapters.find(c => c.id === chapterId);
  const completed = progress.completed;
  const membershipStatus = progress.membershipStatus || 'free';

  // 応用コース前提条件チェック
  const isAppliedChapter = ch && ch.courseType === 'applied';
  const basicChapters = isAppliedChapter
    ? chapters.filter(function(c) { return c.courseType === 'basic'; })
    : [];
  const basicFlat = isAppliedChapter
    ? basicChapters.reduce(function(acc, c) { return acc.concat(c.lessons); }, [])
    : [];
  const allBasicCleared = isAppliedChapter
    ? basicFlat.every(function(l) { return isLessonCleared(l.slug, lessonDetails, progress); })
    : true;

  if (!ch) return <div className="main-area"><p>チャプターが見つかりません</p></div>;

  const prevCh = chapters.find(c => c.id === chapterId - 1);
  const nextCh = chapters.find(c => c.id === chapterId + 1);
  const { status, progress: pct, done } = chapterStatus(ch, completed);

  const allDone = done === ch.sectorCount;

  return (
    <main className="main-area">
      <ChDetailStyles />

      {/* ── ヘッダー ── */}
      <div className="chd-header">
        <button className="chd-back" onClick={() => nav.goAbout()}>← トップへ</button>
        <div className="chd-hero">
          <div className="chd-icon">{ch.icon}</div>
          <div>
            <div className="chd-chapter-label">{ch.isBonus ? '番外編' : `Chapter ${ch.id}`}</div>
            <h1 className="chd-title">{ch.title}</h1>
            <p className="chd-subtitle">{ch.subtitle}</p>
          </div>
        </div>

        {/* 進捗バー */}
        <div className="chd-progress-wrap">
          <div className="chd-progress-bar">
            <div className="chd-progress-fill" style={{ width: pct + "%" }} />
          </div>
          <span className="chd-progress-txt">{done} / {ch.sectorCount} セクター完了</span>
        </div>
      </div>

      {/* ── 応用コース前提条件バナー ── */}
      {isAppliedChapter && !allBasicCleared && (
        <div className="chd-prereq-banner">
          <span className="chd-prereq-icon">📚</span>
          <div className="chd-prereq-body">
            <strong>基礎コース修了が必要です</strong>
            <p>「はじめに」〜「スタイル」の全セクターをクリアすると、このコースが解放されます。</p>
          </div>
        </div>
      )}

      {/* ── セクターリスト ── */}
      <div className="chd-list">
        {ch.lessons.map((lesson, idx) => {
          const detail       = lessonDetails[lesson.slug];
          const hasQuiz      = !!(detail?.hasQuiz || detail?.quiz?.length > 0);
          const isCleared    = isLessonCleared(lesson.slug, lessonDetails, progress);
          const isStepLock   = !isLessonAccessible(idx, ch.lessons, lessonDetails, progress);
          const isMemberLock = lesson.access === 'paid' && membershipStatus !== 'active';
          const isLocked     = isStepLock; // ステップロックのみ click 無効（会員ロックは遷移してCTAを表示）
          const canAccess    = !isLocked;

          return (
            <div
              key={lesson.slug}
              className={`chd-sector ${isCleared ? "done" : ""} ${isLocked ? "locked" : ""} ${canAccess ? "clickable" : ""}`}
              onClick={() => canAccess && nav.goLesson(lesson.slug, chapterId)}
            >
              <div className="chd-sector-num">
                {isCleared
                  ? <span className="chd-check">✓</span>
                  : (isLocked || isMemberLock)
                    ? <span className="chd-lock">🔒</span>
                    : <span className="chd-order">{idx + 1}</span>}
              </div>

              <div className="chd-sector-body">
                <div className="chd-sector-title">{lesson.title}</div>
                <div className="chd-sector-sub">{lesson.subtitle}</div>
                <div className="chd-sector-meta">
                  {lesson.isFree && <span className="tag tag-free">無料</span>}
                  {!lesson.isFree && <span className="tag tag-paid">有料</span>}
                  {hasQuiz && <span className="tag tag-quiz">📝 テスト</span>}
                </div>
              </div>

              <div className="chd-sector-arrow">
                {canAccess ? "›" : ""}
              </div>
            </div>
          );
        })}
      </div>

      {/* ── チャプターナビ ── */}
      <div className="chd-chapter-nav">
        {prevCh && (
          <button className="chd-nav-btn" onClick={() => nav.goChapter(prevCh.id)}>
            ← {prevCh.title}
          </button>
        )}
        <div style={{ flex: 1 }} />
        {allDone && nextCh && (
          <button className="chd-nav-btn primary" onClick={() => nav.goChapter(nextCh.id)}>
            次へ: {nextCh.title} →
          </button>
        )}
      </div>
    </main>
  );
}

function ChDetailStyles() {
  return (
    <style>{`
      .chd-header {
        background: var(--navy-900);
        color: white;
        padding: 28px 32px 24px;
        border-radius: 16px;
        margin-bottom: 24px;
      }
      .chd-back {
        background: none; border: none; color: rgba(255,255,255,.65);
        font-size: 13px; cursor: pointer; padding: 0; margin-bottom: 16px;
        display: block;
      }
      .chd-back:hover { color: white; }
      .chd-hero { display: flex; align-items: center; gap: 20px; margin-bottom: 20px; }
      .chd-icon { font-size: 48px; line-height: 1; }
      .chd-chapter-label { font-size: 11px; text-transform: uppercase; letter-spacing: .1em; color: var(--gold-400); margin-bottom: 4px; }
      .chd-title { font-size: 28px; font-weight: 800; margin: 0 0 4px; }
      .chd-subtitle { font-size: 14px; color: rgba(255,255,255,.7); margin: 0; }
      .chd-progress-wrap { display: flex; align-items: center; gap: 12px; }
      .chd-progress-bar { flex: 1; height: 8px; background: rgba(255,255,255,.18); border-radius: 99px; overflow: hidden; }
      .chd-progress-fill { height: 100%; background: var(--gold-400); border-radius: 99px; transition: width .4s; }
      .chd-progress-txt { font-size: 12px; color: rgba(255,255,255,.7); white-space: nowrap; }

      .chd-prereq-banner {
        display: flex; align-items: flex-start; gap: 14px;
        background: var(--navy-50, #eef2ff); border: 2px solid var(--navy-200);
        border-radius: 12px; padding: 16px 20px; margin-bottom: 20px;
      }
      .chd-prereq-icon { font-size: 28px; flex-shrink: 0; }
      .chd-prereq-body strong { font-size: 14px; font-weight: 800; color: var(--navy-900); display: block; margin-bottom: 4px; }
      .chd-prereq-body p { font-size: 13px; color: var(--ink-500); margin: 0; line-height: 1.6; }

      .chd-list { display: flex; flex-direction: column; gap: 10px; margin-bottom: 32px; }

      .chd-sector {
        background: white; border-radius: 12px; display: flex; align-items: center;
        padding: 16px 20px; gap: 16px; border: 2px solid transparent;
        box-shadow: 0 1px 4px rgba(0,0,0,.06);
        transition: border-color .15s, box-shadow .15s;
      }
      .chd-sector.clickable { cursor: pointer; }
      .chd-sector.clickable:hover { border-color: var(--navy-200); box-shadow: 0 4px 12px rgba(0,0,0,.1); }
      .chd-sector.done { background: var(--green-50, #f0fdf4); border-color: var(--green-200, #bbf7d0); }
      .chd-sector.locked { opacity: .55; cursor: not-allowed; }

      .chd-sector-num {
        width: 36px; height: 36px; border-radius: 50%;
        background: var(--navy-100); display: flex; align-items: center; justify-content: center;
        font-weight: 700; font-size: 15px; color: var(--navy-700); flex-shrink: 0;
      }
      .chd-sector.done .chd-sector-num { background: var(--green-500, #22c55e); color: white; }
      .chd-check { font-size: 16px; }
      .chd-lock { font-size: 14px; }
      .chd-order { font-size: 14px; }

      .chd-sector-body { flex: 1; min-width: 0; }
      .chd-sector-title { font-size: 15px; font-weight: 700; color: var(--navy-900); margin-bottom: 2px; }
      .chd-sector-sub { font-size: 12px; color: var(--ink-400); margin-bottom: 6px; }
      .chd-sector-meta { display: flex; gap: 6px; flex-wrap: wrap; }

      .tag-free  { background: var(--green-100, #dcfce7); color: var(--green-700, #15803d); }
      .tag-paid  { background: var(--gold-100, #fef9c3); color: var(--gold-700, #a16207); }
      .tag-quiz  { background: var(--navy-100); color: var(--navy-700); }

      .chd-sector-arrow { font-size: 22px; color: var(--ink-300); flex-shrink: 0; }

      .chd-chapter-nav { display: flex; align-items: center; gap: 12px; padding: 8px 0 24px; }
      .chd-nav-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;
        transition: background .15s;
      }
      .chd-nav-btn:hover { background: var(--navy-50); }
      .chd-nav-btn.primary { background: var(--navy-900); color: white; border-color: var(--navy-900); }
      .chd-nav-btn.primary:hover { background: var(--navy-700); }

      @media(max-width:768px){
        .chd-header { padding: 20px 16px 18px; border-radius: 12px; margin-bottom: 16px; }
        .chd-title { font-size: 22px; word-break: break-word; overflow-wrap: break-word; }
        .chd-subtitle { word-break: break-word; overflow-wrap: break-word; }
        .chd-icon { font-size: 36px; }
        .chd-sector { padding: 14px 14px; gap: 12px; overflow: hidden; }
        .chd-sector-num { width: 30px; height: 30px; font-size: 13px; flex-shrink: 0; }
        .chd-sector-title { font-size: 14px; word-break: break-word; overflow-wrap: break-word; }
        .chd-sector-sub { word-break: break-word; overflow-wrap: break-word; }
        .chd-sector-body { min-width: 0; }
        .chd-chapter-nav { flex-direction: column; gap: 8px; }
        .chd-nav-btn { width: 100%; text-align: center; word-break: break-word; }
      }
      @media(max-width:480px){
        .chd-header { padding: 16px 12px 14px; }
        .chd-title { font-size: 19px; }
      }
    `}</style>
  );
}

window.ChapterDetail = ChapterDetail;
