/* 応用コース ページ */

function AppliedCourse({ nav, progress }) {
  const chapters  = window.APP_DATA.chapters;
  const completed = progress ? progress.completed : [];

  const basicChapters   = chapters.filter(ch => !ch.isBonus && !ch.isIntro);
  const isBasicComplete = basicChapters.every(ch => chapterStatus(ch, completed).status === "done");
  const basicDoneCount  = basicChapters.filter(ch => chapterStatus(ch, completed).status === "done").length;
  const basicTotal      = basicChapters.length;
  const basicPct        = Math.round(basicDoneCount / basicTotal * 100);

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

      {isBasicComplete ? <ApUnlocked nav={nav} /> : <ApLocked basicDoneCount={basicDoneCount} basicTotal={basicTotal} basicPct={basicPct} nav={nav} />}
    </main>
  );
}

/* ── ロック画面 ─────────────────────────────────────────────── */
function ApLocked({ basicDoneCount, basicTotal, basicPct, nav }) {
  return (
    <div className="ap-lock-wrap">
      <div className="ap-lock-icon">🔒</div>
      <h1 className="ap-lock-title">応用コース</h1>
      <p className="ap-lock-desc">基礎コース（CH.01〜CH.07）をすべて修了すると<br />解放されます</p>

      <div className="ap-lock-progress">
        <div className="ap-lp-bar">
          <div className="ap-lp-fill" style={{ width: basicPct + "%" }} />
        </div>
        <div className="ap-lp-text">
          <span>{basicDoneCount} / {basicTotal} チャプター完了</span>
          <span>あと {basicTotal - basicDoneCount} チャプター</span>
        </div>
      </div>

      <button className="btn btn-primary ap-lock-btn" onClick={() => nav.goChapter(1)}>
        基礎コースを続ける →
      </button>
    </div>
  );
}

/* ── 解放後（手法スロット）────────────────────────────────── */
// sectors が空なら「近日公開」、埋まっていればアコーディオンでS1〜展開
function buildApCourses(chapters) {
  const tc1Ch = chapters.find(ch => ch.prefix === 'tc1');
  const tc2Ch = chapters.find(ch => ch.prefix === 'tc2');
  const fc1Ch = chapters.find(ch => ch.prefix === 'fc1');
  const fc2Ch = chapters.find(ch => ch.prefix === 'fc2');
  const tc3Ch = chapters.find(ch => ch.prefix === 'tc3');
  const fc3Ch = chapters.find(ch => ch.prefix === 'fc3');
  const fc4Ch = chapters.find(ch => ch.prefix === 'fc4');
  return [
    {
      id: "technical",
      title: "テクニカルコース",
      subtitle: "チャートと売買タイミングを極める",
      icon: "📈",
      color: "navy",
      methods: [
        {
          id: "tc-1",
          title: "迷ったらこれから！テクニカル分析実践攻略",
          chId: tc1Ch ? tc1Ch.id : null,
          sectors: tc1Ch ? tc1Ch.lessons : [],
        },
        {
          id: "tc-2",
          title: "トレンドの始まりを読み解く　初動キャッチ手法",
          chId: tc2Ch ? tc2Ch.id : null,
          sectors: tc2Ch ? tc2Ch.lessons : [],
        },
        { id: "tc-3", title: "複数視点から考える分析手法", chId: tc3Ch ? tc3Ch.id : null, sectors: tc3Ch ? tc3Ch.lessons : [] },
      ],
    },
    {
      id: "fundamental",
      title: "ファンダメンタルコース",
      subtitle: "企業価値を見抜いて長期投資を極める",
      icon: "🏛",
      color: "gold",
      methods: [
        {
          id: "fc-1",
          title: "迷ったらこれから！ファンダメンタル分析実践攻略",
          chId: fc1Ch ? fc1Ch.id : null,
          sectors: fc1Ch ? fc1Ch.lessons : [],
        },
        {
          id: "fc-2",
          title: "トレンドを読み解く　テーマ株投資手法",
          chId: fc2Ch ? fc2Ch.id : null,
          sectors: fc2Ch ? fc2Ch.lessons : [],
        },
        { id: "fc-3", title: "これから伸びる会社を狙う 成長株投資手法", chId: fc3Ch ? fc3Ch.id : null, sectors: fc3Ch ? fc3Ch.lessons : [] },
        { id: "fc-4", title: "IPO株で大化け株を狙う テンバガー発掘手法", chId: fc4Ch ? fc4Ch.id : null, sectors: fc4Ch ? fc4Ch.lessons : [] },
      ],
    },
  ];
}

function ApUnlocked({ nav }) {
  const chapters = window.APP_DATA.chapters;
  const courses = buildApCourses(chapters);
  return (
    <div className="ap-unlock-wrap">
      <div className="ap-unlock-header">
        <div className="ap-unlock-badge">🎉 解放済み</div>
        <h1 className="ap-unlock-title">応用コース</h1>
        <p className="ap-unlock-desc">自分のスタイルに合ったコースから始めよう</p>
      </div>

      <div className="ap-course-grid">
        {courses.map(c => <ApCourseCard key={c.id} course={c} nav={nav} />)}
      </div>
    </div>
  );
}

function ApCourseCard({ course, nav }) {
  const [openMethodId, setOpenMethodId] = React.useState(null);

  const toggleMethod = (id, hasSectors) => {
    if (!hasSectors) return;
    setOpenMethodId(openMethodId === id ? null : id);
  };

  return (
    <div className={`ap-card ap-card-${course.color}`}>
      <div className="ap-card-header">
        <span className="ap-card-icon">{course.icon}</span>
        <div>
          <div className="ap-card-title">{course.title}</div>
          <div className="ap-card-subtitle">{course.subtitle}</div>
        </div>
      </div>
      <div className="ap-sector-list">
        {course.methods.map((m, i) => {
          const hasSectors = m.sectors.length > 0;
          const isOpen = openMethodId === m.id;
          return (
            <React.Fragment key={m.id}>
              <div
                className={`ap-sector-row ap-method-row${hasSectors ? " ap-method-active" : ""}`}
                onClick={() => toggleMethod(m.id, hasSectors)}
                style={hasSectors ? { cursor: "pointer" } : {}}
              >
                <span className={`ap-sector-num${hasSectors ? " ap-sector-num-active" : ""}`}>{i + 1}</span>
                <span className={`ap-sector-label${hasSectors ? " ap-sector-label-active" : ""}`}>{m.title}</span>
                {hasSectors
                  ? <span className="ap-sector-badge ap-badge-open">
                      {isOpen ? "▲ 閉じる" : `全${m.sectors.length}回 ▼`}
                    </span>
                  : <span className="ap-sector-badge">近日公開</span>
                }
              </div>
              {isOpen && hasSectors && (
                <div className="ap-sub-list">
                  {m.sectors.map((s, si) => {
                    const shortTitle = s.title.replace(/^(テクニカル|ファンダメンタル)実践攻略 セクター\d+[：:]/, "");
                    return (
                      <div
                        key={s.slug}
                        className="ap-sub-row"
                        onClick={() => nav.goLesson(s.slug, m.chId)}
                      >
                        <span className="ap-sub-num">S{si + 1}</span>
                        <span className="ap-sub-label">{shortTitle}</span>
                        <span className="ap-sub-arrow">▶</span>
                      </div>
                    );
                  })}
                </div>
              )}
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
}

/* ── スタイル ────────────────────────────────────────────────── */
function ApStyles() {
  return (
    <style>{`
      /* ── ロック画面 ── */
      .ap-lock-wrap {
        display: flex; flex-direction: column; align-items: center;
        padding: 60px 24px 80px; text-align: center; max-width: 440px; margin: 0 auto;
      }
      .ap-lock-icon { font-size: 64px; margin-bottom: 20px; }
      .ap-lock-title { font-size: 28px; font-weight: 800; color: var(--navy-900); margin: 0 0 12px; }
      .ap-lock-desc { font-size: 15px; color: var(--ink-500); line-height: 1.7; margin: 0 0 32px; }

      .ap-lock-progress { width: 100%; margin-bottom: 32px; }
      .ap-lp-bar { height: 10px; background: var(--ink-100); border-radius: 99px; overflow: hidden; margin-bottom: 8px; }
      .ap-lp-fill { height: 100%; background: var(--navy-600); border-radius: 99px; transition: width .4s; }
      .ap-lp-text { display: flex; justify-content: space-between; font-size: 12px; color: var(--ink-500); }

      .ap-lock-btn { width: 100%; max-width: 300px; }

      /* ── 解放後 ── */
      .ap-unlock-wrap { padding: 0 0 40px; }
      .ap-unlock-header {
        background: var(--navy-900); color: white;
        padding: 28px 32px 24px; border-radius: 16px; margin-bottom: 24px;
      }
      .ap-unlock-badge {
        display: inline-block; background: var(--gold-400); color: var(--navy-900);
        font-size: 12px; font-weight: 800; padding: 3px 12px; border-radius: 99px;
        margin-bottom: 12px;
      }
      .ap-unlock-title { font-size: 26px; font-weight: 800; margin: 0 0 6px; }
      .ap-unlock-desc { font-size: 14px; color: rgba(255,255,255,.7); margin: 0; }

      .ap-course-grid { display: flex; flex-direction: column; gap: 20px; }

      /* ── コースカード ── */
      .ap-card {
        background: white; border-radius: 16px;
        border: 2px solid var(--ink-100);
        box-shadow: var(--shadow-sm); overflow: hidden;
      }
      .ap-card-header {
        display: flex; align-items: center; gap: 16px;
        padding: 20px 24px 16px;
      }
      .ap-card-navy .ap-card-header { background: linear-gradient(135deg, #0F1F4D, #1E3A8A); color: white; }
      .ap-card-gold .ap-card-header { background: linear-gradient(135deg, #a16207, #D88718); color: white; }
      .ap-card-icon { font-size: 40px; flex-shrink: 0; }
      .ap-card-title { font-size: 18px; font-weight: 800; margin-bottom: 4px; }
      .ap-card-subtitle { font-size: 12px; opacity: .8; }

      .ap-sector-list { padding: 12px 16px 16px; display: flex; flex-direction: column; gap: 8px; }
      .ap-sector-row {
        display: flex; align-items: center; gap: 12px;
        padding: 10px 14px; border-radius: 10px;
        background: var(--ink-50); border: 1px solid var(--ink-100);
      }
      .ap-sector-num {
        width: 24px; height: 24px; border-radius: 50%;
        background: var(--ink-200); color: var(--ink-500);
        font-size: 11px; font-weight: 700; display: flex; align-items: center; justify-content: center;
        flex-shrink: 0;
      }
      .ap-sector-label { flex: 1; font-size: 13px; font-weight: 600; color: var(--ink-500); }
      .ap-sector-badge {
        font-size: 10px; font-weight: 700; padding: 2px 8px; border-radius: 99px;
        background: var(--ink-200); color: var(--ink-500); white-space: nowrap;
      }
      .ap-badge-open {
        background: var(--navy-100, #dbeafe); color: var(--navy-700, #1d4ed8);
      }
      .ap-method-active {
        background: var(--ink-50); border-color: var(--navy-200, #bfdbfe);
      }
      .ap-sector-num-active {
        background: var(--navy-600); color: white;
      }
      .ap-sector-label-active {
        color: var(--navy-900); font-weight: 700;
      }

      /* サブセクター（S1〜S8）リスト */
      .ap-sub-list {
        display: flex; flex-direction: column; gap: 4px;
        padding: 6px 0 4px 36px;
      }
      .ap-sub-row {
        display: flex; align-items: center; gap: 10px;
        padding: 9px 12px; border-radius: 8px;
        background: white; border: 1px solid var(--ink-100);
        cursor: pointer; transition: background .15s;
      }
      .ap-sub-row:hover { background: var(--navy-50, #eff6ff); border-color: var(--navy-200, #bfdbfe); }
      .ap-sub-num {
        width: 28px; height: 20px; border-radius: 4px;
        background: var(--navy-100, #dbeafe); color: var(--navy-700, #1d4ed8);
        font-size: 10px; font-weight: 800; display: flex; align-items: center; justify-content: center;
        flex-shrink: 0;
      }
      .ap-sub-label { flex: 1; font-size: 12px; font-weight: 600; color: var(--ink-800); }
      .ap-sub-arrow { font-size: 10px; color: var(--navy-400, #93c5fd); flex-shrink: 0; }

      @media(max-width:768px){
        .ap-lock-wrap { padding: 40px 16px 60px; }
        .ap-lock-icon { font-size: 52px; }
        .ap-lock-title { font-size: 24px; }
        .ap-unlock-header { padding: 20px 16px 18px; border-radius: 12px; }
        .ap-unlock-title { font-size: 22px; }
        .ap-card-header { padding: 16px 16px 14px; gap: 12px; }
        .ap-card-icon { font-size: 32px; }
        .ap-card-title { font-size: 16px; }
        .ap-sector-list { padding: 10px 12px 14px; gap: 6px; }
        .ap-sector-row { padding: 8px 10px; gap: 10px; }
        .ap-sector-label { font-size: 12px; }
      }
    `}</style>
  );
}

window.AppliedCourse = AppliedCourse;
