/* Page: 学習中（StudyingPage） */

// calcStreak を page-badges.jsx から独立して再実装（kabujiro_study_dates 使用）
function calcStreakStudying() {
  try {
    const raw   = localStorage.getItem('kabujiro_study_dates');
    const dates = raw ? JSON.parse(raw) : [];
    if (!dates.length) return 0;
    const sorted = [...new Set(dates)].sort().reverse();
    const today  = new Date().toISOString().slice(0, 10);
    if (sorted[0] !== today) return 0;
    let streak = 1;
    for (let i = 1; i < sorted.length; i++) {
      const diff = (new Date(sorted[i - 1]) - new Date(sorted[i])) / 86400000;
      if (diff === 1) streak++;
      else break;
    }
    return streak;
  } catch { return 0; }
}

// 円グラフ（SVGリング）
function RingChart({ pct, color }) {
  const r     = 15.5;
  const circ  = 2 * Math.PI * r; // ≈ 97.4
  const offset = circ * (1 - pct / 100);
  return (
    <svg width="52" height="52" viewBox="0 0 36 36" style={{ flexShrink: 0 }}>
      <circle cx="18" cy="18" r={r} fill="none" stroke="var(--ink-100)" strokeWidth="4" />
      <circle cx="18" cy="18" r={r} fill="none" stroke={color} strokeWidth="4"
        strokeLinecap="round"
        strokeDasharray={`${circ.toFixed(1)}`}
        strokeDashoffset={`${offset.toFixed(1)}`}
        transform="rotate(-90 18 18)" />
      <text x="18" y="21.5" textAnchor="middle" fontSize="9" fontWeight="800"
        fill="var(--ink-900)">{pct}%</text>
    </svg>
  );
}

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

  // ── 1. 続きから ──────────────────────────────────────────
  let continueChapter = null;
  let continueLesson  = null;
  outer: for (const ch of chapters) {
    const st = chapterStatus(ch, completed);
    if (st.status === 'done') continue;
    for (const l of ch.lessons) {
      if (!completed.includes(l.slug)) {
        continueChapter = ch;
        continueLesson  = l;
        break outer;
      }
    }
  }

  // ── 2. 全体進捗 ──────────────────────────────────────────
  const totalSectors = chapters.reduce((s, c) => s + c.sectorCount, 0);
  const doneSectors  = completed.length;
  const totalPct     = totalSectors > 0 ? Math.round(doneSectors / totalSectors * 100) : 0;

  // ── 3. コース別進捗 ───────────────────────────────────────
  const kisoChapters   = chapters.filter(ch => !ch.isBonus && !ch.isApplied && !ch.isIntro);
  const bangaiChapters = chapters.filter(ch =>  ch.isBonus && !ch.isApplied);
  const oyoChapters    = chapters.filter(ch =>  ch.isApplied);

  function coursePct(chs) {
    const total = chs.reduce((s, c) => s + c.sectorCount, 0);
    const done  = chs.reduce((s, c) => s + chapterStatus(c, completed).done, 0);
    return total > 0 ? Math.round(done / total * 100) : 0;
  }

  const kisoPct   = coursePct(kisoChapters);
  const bangaiPct = coursePct(bangaiChapters);
  const oyoPct    = coursePct(oyoChapters);

  // ── 4. 学習中の章 ─────────────────────────────────────────
  const activeChapters = chapters.filter(ch => {
    const st = chapterStatus(ch, completed);
    return st.status === 'active' && st.done > 0;
  });

  function chapterColor(ch) {
    if (ch.isApplied) return '#1F6F5C';
    if (ch.isBonus)   return '#C9731A';
    return '#2E6FD6';
  }

  function courseLabel(ch) {
    if (ch.isApplied) return '応用';
    if (ch.isBonus)   return '番外編';
    if (ch.isIntro)   return 'イントロ';
    return '基礎';
  }

  // ── 5. バッジ（次に取れそうなもの）─────────────────────────
  const basicChapters  = chapters.filter(ch => !ch.isBonus && !ch.isIntro && !ch.isApplied);
  const isBasicDone    = basicChapters.every(ch => chapterStatus(ch, completed).status === 'done');
  const basicDoneCount = basicChapters.filter(ch => chapterStatus(ch, completed).status === 'done').length;
  const streak         = calcStreakStudying();

  const milestones = [
    {
      icon: '📖', name: 'コツコツ習慣',
      earned: doneSectors >= 10,
      hint: `あと ${Math.max(0, 10 - doneSectors)} セクター`,
    },
    {
      icon: '🎯', name: '学びの達人',
      earned: doneSectors >= 50,
      hint: `${doneSectors}/50 セクター`,
    },
    {
      icon: '🏆', name: '基礎コース修了',
      earned: isBasicDone,
      hint: `CH.01〜07完了（${basicDoneCount}/7）`,
    },
    {
      icon: '👑', name: '完全制覇',
      earned: doneSectors >= totalSectors,
      hint: `${doneSectors}/${totalSectors} セクター`,
    },
    {
      icon: '🔥', name: '7日連続',
      earned: streak >= 7,
      hint: streak > 0 ? `あと ${7 - streak} 日` : '学習を重ねて記録',
    },
    {
      icon: '🌟', name: '30日連続',
      earned: streak >= 30,
      hint: streak > 0 ? `${streak}/30 日` : '学習を重ねて記録',
    },
  ];
  const nextBadge = milestones.find(m => !m.earned);

  // ── 6. ストリーク ─────────────────────────────────────────
  const streakMsg = streak === 0
    ? '今日から学習記録スタート！'
    : streak === 1
      ? '今日も学習しました。明日も続けよう！'
      : `${streak}日連続で学習中！この調子でコツコツ続けよう`;

  return (
    <main className="content" style={{ paddingBottom: 32 }}>
      <StudyingStyles />

      <div className="std-wrap">
        <div className="std-title">学習中</div>

        {/* 1. 続きから */}
        {continueLesson ? (
          <div className="std-card std-resume">
            <div className="std-resume-label">続きから学ぶ</div>
            <div className="std-resume-course">
              {courseLabel(continueChapter)} ・ {continueChapter.title}
            </div>
            <div className="std-resume-title">{continueLesson.title}</div>
            <button className="std-resume-btn"
              onClick={() => nav.goLesson(continueLesson.slug, continueChapter.id)}>
              つづきを学ぶ →
            </button>
          </div>
        ) : (
          <div className="std-card std-resume">
            <div className="std-resume-label">🎉 全セクター完了！</div>
            <div className="std-resume-title">
              おめでとうございます！<br />すべての学習を修了しました
            </div>
            <button className="std-resume-btn" onClick={() => nav.goHome()}>
              ホームに戻る
            </button>
          </div>
        )}

        {/* 2. 全体進捗 */}
        <div className="std-card">
          <div className="std-sec-h">全体の進捗</div>
          <div className="std-overall-top">
            <div className="std-overall-num">
              {doneSectors}<small> / {totalSectors} セクター</small>
            </div>
            <div className="std-overall-pct">{totalPct}%</div>
          </div>
          <div className="std-bar">
            <div className="std-bar-fill std-bar-total" style={{ width: `${totalPct}%` }} />
          </div>
        </div>

        {/* 3. コース別進捗 */}
        <div className="std-card">
          <div className="std-sec-h">コース別の進捗</div>
          <div className="std-crow">
            <div className="std-crow-nm">基礎</div>
            <div className="std-crow-b">
              <div className="std-crow-fill std-c-kiso" style={{ width: `${kisoPct}%` }} />
            </div>
            <div className="std-crow-pc">{kisoPct}%</div>
          </div>
          {bangaiChapters.length > 0 && (
            <div className="std-crow">
              <div className="std-crow-nm">番外編</div>
              <div className="std-crow-b">
                <div className="std-crow-fill std-c-bangai" style={{ width: `${bangaiPct}%` }} />
              </div>
              <div className="std-crow-pc">{bangaiPct}%</div>
            </div>
          )}
          {oyoChapters.length > 0 && (
            <div className="std-crow">
              <div className="std-crow-nm">応用</div>
              <div className="std-crow-b">
                <div className="std-crow-fill std-c-oyo" style={{ width: `${oyoPct}%` }} />
              </div>
              <div className="std-crow-pc">{oyoPct}%</div>
            </div>
          )}
        </div>

        {/* 4. 学習中の章 */}
        {activeChapters.length > 0 && (
          <div className="std-card">
            <div className="std-sec-h">学習中のコース</div>
            {activeChapters.map((ch, i) => {
              const st    = chapterStatus(ch, completed);
              const color = chapterColor(ch);
              return (
                <div key={ch.id}
                  className={`std-chap${i > 0 ? ' std-chap-border' : ''}`}
                  onClick={() => nav.goChapter(ch.id)}
                  role="button"
                  tabIndex={0}
                  onKeyDown={e => e.key === 'Enter' && nav.goChapter(ch.id)}>
                  <RingChart pct={st.progress} color={color} />
                  <div className="std-chap-info">
                    <div className="std-chap-ct">{ch.title}</div>
                    <div className="std-chap-cs">
                      {courseLabel(ch)} ・ {st.done} / {ch.sectorCount} セクター
                    </div>
                  </div>
                  <div className="std-chap-go" aria-hidden="true">›</div>
                </div>
              );
            })}
          </div>
        )}

        {/* 5. バッジ導線 */}
        {nextBadge && (
          <div className="std-card">
            <div className="std-sec-h">もうすぐ取れるバッジ</div>
            <div className="std-badge-row">
              <div className="std-badge-ic">{nextBadge.icon}</div>
              <div className="std-badge-tx">
                <div className="std-badge-bt">{nextBadge.name}</div>
                <div className="std-badge-bs">{nextBadge.hint}</div>
              </div>
            </div>
            <button className="std-badge-link" onClick={() => nav.goBadges()}>
              獲得したバッジを見る →
            </button>
          </div>
        )}

        {/* 6. ストリーク */}
        <div className="std-card">
          <div className="std-sec-h">学習の記録</div>
          <div className="std-streak">
            <div className="std-streak-fire">🔥</div>
            <div>
              <div className="std-streak-days">
                {streak}<small> 日連続</small>
              </div>
              <div className="std-streak-sub">{streakMsg}</div>
            </div>
          </div>
        </div>

      </div>
    </main>
  );
}

function StudyingStyles() {
  return <style>{`
    .std-wrap { max-width: 480px; margin: 0 auto; padding: 4px 0 16px; }
    .std-title { font-size: 20px; font-weight: 800; margin: 8px 4px 16px; color: var(--ink-900); }

    .std-card {
      background: var(--white);
      border-radius: var(--radius-lg);
      padding: 18px;
      margin-bottom: 14px;
      box-shadow: var(--shadow-sm);
      border: 1px solid var(--ink-100);
    }
    .std-sec-h {
      font-size: 12px; font-weight: 800;
      color: var(--ink-500); letter-spacing: .05em;
      margin-bottom: 10px; text-transform: uppercase;
    }

    /* 1. 続きから */
    .std-resume { background: linear-gradient(135deg, #1F6F5C, #13294B); border: none; color: #fff; }
    .std-resume-label { font-size: 11.5px; color: #B8E0D4; font-weight: 700; letter-spacing: .05em; }
    .std-resume-course { font-size: 11px; color: #9FD9C6; margin-top: 10px; }
    .std-resume-title { font-size: 17px; font-weight: 800; margin: 4px 0 14px; line-height: 1.4; }
    .std-resume-btn {
      display: block; width: 100%;
      background: #fff; color: #13294B;
      text-align: center; font-weight: 800; font-size: 15px;
      padding: 13px; border-radius: 11px;
      border: none; cursor: pointer; font-family: var(--font-jp);
      transition: opacity .15s;
    }
    .std-resume-btn:hover { opacity: .9; }

    /* 2. 全体進捗 */
    .std-overall-top { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 10px; }
    .std-overall-num { font-size: 24px; font-weight: 800; color: #1F6F5C; }
    .std-overall-num small { font-size: 13px; color: var(--ink-500); font-weight: 700; }
    .std-overall-pct { font-size: 15px; font-weight: 800; color: var(--gold-600); }
    .std-bar { height: 12px; background: var(--ink-100); border-radius: 99px; overflow: hidden; }
    .std-bar-fill { height: 100%; border-radius: 99px; transition: width .4s ease; }
    .std-bar-total { background: linear-gradient(90deg, #1F6F5C, #3E8B72); }

    /* 3. コース別 */
    .std-crow { display: flex; align-items: center; gap: 12px; margin: 12px 0; }
    .std-crow:first-of-type { margin-top: 4px; }
    .std-crow-nm { width: 50px; font-size: 12px; font-weight: 800; color: var(--ink-700); }
    .std-crow-b { flex: 1; height: 9px; background: var(--ink-100); border-radius: 99px; overflow: hidden; }
    .std-crow-fill { height: 100%; border-radius: 99px; transition: width .4s ease; }
    .std-crow-pc { width: 36px; text-align: right; font-size: 12px; font-weight: 800; color: var(--ink-500); }
    .std-c-kiso   { background: #2E6FD6; }
    .std-c-bangai { background: #C9731A; }
    .std-c-oyo    { background: #1F6F5C; }

    /* 4. 学習中の章 */
    .std-chap { display: flex; align-items: center; gap: 14px; padding: 12px 0; cursor: pointer; }
    .std-chap-border { border-top: 1px solid var(--ink-100); }
    .std-chap:hover { opacity: .8; }
    .std-chap-info { flex: 1; min-width: 0; }
    .std-chap-ct { font-size: 14px; font-weight: 800; color: var(--ink-900); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .std-chap-cs { font-size: 11.5px; color: var(--ink-500); margin-top: 2px; }
    .std-chap-go { color: var(--ink-300); font-size: 20px; font-weight: 800; line-height: 1; }

    /* 5. バッジ */
    .std-badge-row { display: flex; gap: 12px; align-items: center; }
    .std-badge-ic {
      width: 46px; height: 46px; border-radius: 12px;
      background: var(--gold-100);
      display: flex; align-items: center; justify-content: center;
      font-size: 24px; flex-shrink: 0;
    }
    .std-badge-tx { flex: 1; }
    .std-badge-bt { font-size: 13.5px; font-weight: 800; color: var(--ink-900); }
    .std-badge-bs { font-size: 11.5px; color: var(--ink-500); margin-top: 2px; }
    .std-badge-link {
      display: block; width: 100%; background: none; border: none;
      text-align: center; margin-top: 12px; color: #1F6F5C;
      font-weight: 800; font-size: 13.5px;
      padding-top: 12px; border-top: 1px solid var(--ink-100);
      cursor: pointer; font-family: var(--font-jp);
    }
    .std-badge-link:hover { opacity: .7; }

    /* 6. ストリーク */
    .std-streak { display: flex; align-items: center; gap: 14px; }
    .std-streak-fire { font-size: 34px; line-height: 1; }
    .std-streak-days { font-size: 28px; font-weight: 800; color: #C9731A; line-height: 1.2; }
    .std-streak-days small { font-size: 13px; color: var(--ink-500); font-weight: 700; }
    .std-streak-sub { font-size: 12px; color: var(--ink-700); margin-top: 4px; }

    /* レスポンシブ */
    @media (max-width: 640px) {
      .std-wrap { padding: 4px 0 80px; }
    }
  `}</style>;
}
