/* Page: 達成バッジ */

const BADGE_CIRC = 207; // 2π × 33 ≈ 207.3（SVG 円弧の周長）

// ── 連続学習日数を計算 ─────────────────────────────────────────────
function calcStreak() {
  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);
    const yest   = new Date(Date.now() - 86400000).toISOString().slice(0, 10);
    // 今日か昨日に学習していないとストリーク切れ
    if (sorted[0] !== today && sorted[0] !== yest) return 0;
    let streak = 1;
    for (let i = 1; i < sorted.length; i++) {
      const diff = Math.round(
        (new Date(sorted[i - 1]) - new Date(sorted[i])) / 86400000
      );
      if (diff === 1) streak++;
      else break;
    }
    return streak;
  } catch { return 0; }
}

// ── チャプター別 進捗バッジ ────────────────────────────────────────
function ChapterBadge({ ch, completed }) {
  const st     = chapterStatus(ch, completed);
  const done   = st.done;
  const total  = ch.sectorCount;
  const isDone = st.status === 'done';
  const isZero = done === 0;

  const filled = isDone ? BADGE_CIRC : Math.round((done / total) * BADGE_CIRC);
  const arc    = isDone ? '#E0992B' : '#2E6FD6';

  return (
    <div className={`bd-cbadge ${isDone ? 'done' : ''} ${isZero ? 'todo' : ''}`}>
      <div className="bd-cring">
        <svg width="78" height="78" viewBox="0 0 78 78">
          {/* トラック（薄グレー） */}
          <circle cx="39" cy="39" r="33" fill="none" stroke="#E7ECF3" strokeWidth="6" />
          {/* 進捗弧（0のときは非表示） */}
          {!isZero && (
            <circle
              cx="39" cy="39" r="33" fill="none"
              stroke={arc} strokeWidth="6"
              strokeLinecap="round"
              strokeDasharray={`${filled} ${BADGE_CIRC}`}
              transform="rotate(-90 39 39)"
            />
          )}
        </svg>
        <span className="bd-cemoji">{ch.icon}</span>
        {isDone && <span className="bd-cdot">✓</span>}
      </div>
      <div className="bd-cname">{ch.title}</div>
      <div className={`bd-cprog ${isDone ? 'comp' : ''}`}>
        {isDone ? `${total}/${total} 完了` : `${done}/${total}`}
      </div>
    </div>
  );
}

// ── マイルストーン・バイナリバッジ ────────────────────────────────
function MilestoneBadge({ icon, name, earned, condition }) {
  return (
    <div className={`bd-mbadge ${earned ? 'earned' : 'locked'}`}>
      <div className="bd-mring">
        <span className="bd-mico">{icon}</span>
        {earned
          ? <span className="bd-check">✓</span>
          : <span className="bd-lock">🔒</span>
        }
      </div>
      <div className="bd-mname">{name}</div>
      <div className="bd-mcond">{condition}</div>
    </div>
  );
}

// ── メインページ ───────────────────────────────────────────────────
function BadgesPage({ nav, progress }) {
  const chapters = window.APP_DATA.chapters;
  const completed = progress.completed;

  const totalSectors   = chapters.reduce((s, c) => s + c.sectorCount, 0);
  const doneSectors    = completed.length;
  const streak         = calcStreak();

  const basicChapters  = chapters.filter(ch => !ch.isBonus);
  const isBasicDone    = basicChapters.every(ch => chapterStatus(ch, completed).status === 'done');
  const basicDoneCount = basicChapters.filter(ch => chapterStatus(ch, completed).status === 'done').length;

  // サマリー（チャプター単位）
  const chapDoneCount = chapters.filter(ch => chapterStatus(ch, completed).status === 'done').length;
  const chapPct       = chapters.length > 0 ? Math.round(chapDoneCount / chapters.length * 100) : 0;

  // マイルストーン定義
  const milestones = [
    {
      icon: '📖', name: 'コツコツ習慣',
      earned: doneSectors >= 10,
      condition: doneSectors >= 10
        ? '獲得済み'
        : `あと ${10 - doneSectors} セクター`,
    },
    {
      icon: '🎯', name: '学びの達人',
      earned: doneSectors >= 50,
      condition: doneSectors >= 50
        ? '獲得済み'
        : `${doneSectors}/50 セクター`,
    },
    {
      icon: '👑', name: '完全制覇',
      earned: totalSectors > 0 && doneSectors >= totalSectors,
      condition: doneSectors >= totalSectors
        ? '獲得済み'
        : `${doneSectors}/${totalSectors}`,
    },
    {
      icon: '🏆', name: '基礎コース修了',
      earned: isBasicDone,
      condition: isBasicDone
        ? '獲得済み'
        : `CH.01〜07完了 (${basicDoneCount}/7)`,
    },
    {
      icon: '🔥', name: '7日連続',
      earned: streak >= 7,
      condition: streak >= 7
        ? '獲得済み'
        : streak > 0
          ? `あと ${7 - streak} 日`
          : '学習を重ねて記録',
    },
    {
      icon: '🌟', name: '30日連続',
      earned: streak >= 30,
      condition: streak >= 30
        ? '獲得済み'
        : streak > 0
          ? `${streak}/30 日`
          : '学習を重ねて記録',
    },
    {
      icon: '✅', name: 'テスト合格',
      earned: false,
      condition: '近日公開',
    },
  ];

  return (
    <main className="content">
      <BadgeStyles />
      <div className="bd-wrap">

        {/* ── ヘッダー ── */}
        <h1 className="bd-h1">達成バッジ</h1>
        <p className="bd-sub">チャプターを進めるほど、リングが埋まってバッジが光ります。</p>

        {/* ── サマリーカード ── */}
        <div className="bd-summary">
          <div className="bd-sum-row">
            <div className="bd-sum-big">
              {chapDoneCount}<small> / {chapters.length} 章 制覇</small>
            </div>
            <div className="bd-sum-lbl">チャプターバッジ</div>
          </div>
          <div className="bd-bar">
            <i style={{ width: `${Math.max(chapPct, chapDoneCount > 0 ? 3 : 0)}%` }} />
          </div>
        </div>

        {/* ── チャプター別 進捗バッジ ── */}
        <div className="bd-sec">📚 チャプター別 進捗バッジ</div>
        <div className="bd-cgrid">
          {chapters.map(ch => (
            <ChapterBadge key={ch.id} ch={ch} completed={completed} />
          ))}
        </div>

        {/* ── マイルストーン ── */}
        <div className="bd-sec">🌱 マイルストーン・継続・テスト</div>
        <div className="bd-mgrid">
          {milestones.map((m, i) => (
            <MilestoneBadge key={i} {...m} />
          ))}
        </div>

        <p className="bd-note">
          ※ 継続バッジはレッスン完了ごとに学習日が記録され、翌日以降に連続日数へ反映されます。<br />
          ※ テスト合格バッジは総合テスト機能の実装後に有効になります。
        </p>

      </div>
    </main>
  );
}

// ── スタイル ───────────────────────────────────────────────────────
function BadgeStyles() {
  return (
    <style>{`
      .bd-wrap {
        padding: 28px 24px 100px;
        max-width: 620px;
      }

      /* ヘッダー */
      .bd-h1 { font-size: 24px; font-weight: 800; color: var(--navy-900,#13294B); margin: 0 0 4px; }
      .bd-sub { font-size: 13px; color: var(--ink-500,#6B7480); margin: 0 0 20px; line-height: 1.6; }

      /* サマリーカード */
      .bd-summary {
        background: var(--navy-900,#13294B);
        border-radius: 18px; padding: 18px 20px; color: #fff; margin-bottom: 4px;
      }
      .bd-sum-row {
        display: flex; justify-content: space-between; align-items: flex-end; margin-bottom: 10px;
      }
      .bd-sum-big { font-size: 30px; font-weight: 900; line-height: 1; }
      .bd-sum-big small { font-size: 15px; font-weight: 700; opacity: .8; }
      .bd-sum-lbl { font-size: 12px; color: #9FB6D8; }
      .bd-bar {
        height: 8px; border-radius: 99px; background: rgba(255,255,255,.18); overflow: hidden;
      }
      .bd-bar > i {
        display: block; height: 100%; min-width: 0;
        background: linear-gradient(90deg, #F6C551, #E0992B);
        border-radius: 99px; transition: width .6s ease;
      }

      /* セクションラベル */
      .bd-sec {
        font-size: 14px; font-weight: 800; color: var(--navy-900,#13294B);
        margin: 26px 0 14px;
      }

      /* ── チャプター進捗バッジ ── */
      .bd-cgrid {
        display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px 8px;
        margin-bottom: 4px;
      }
      .bd-cbadge { text-align: center; }
      .bd-cring  { position: relative; width: 78px; height: 78px; margin: 0 auto 8px; }

      /* SVG はコンテナに合わせる */
      .bd-cring svg { display: block; width: 78px; height: 78px; }

      /* 中央アイコン */
      .bd-cemoji {
        position: absolute; inset: 0;
        display: flex; align-items: center; justify-content: center;
        font-size: 30px; pointer-events: none;
      }
      .bd-cbadge.todo .bd-cemoji { filter: grayscale(1); opacity: .55; }

      /* 完了✓ドット */
      .bd-cdot {
        position: absolute; right: 2px; bottom: 2px;
        width: 22px; height: 22px; border-radius: 50%;
        background: #1F6F5C; color: #fff;
        display: flex; align-items: center; justify-content: center;
        font-size: 11px; font-weight: 800; border: 2.5px solid #fff;
      }

      .bd-cname { font-size: 12px; font-weight: 700; line-height: 1.3; color: var(--navy-900,#13294B); }
      .bd-cbadge.todo .bd-cname { color: #9AA3AF; }
      .bd-cprog { font-size: 11px; color: var(--ink-400,#9CA3AF); margin-top: 2px; font-weight: 700; }
      .bd-cprog.comp { color: #E0992B; }

      /* ── マイルストーンバッジ ── */
      .bd-mgrid {
        display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px 8px;
      }
      .bd-mbadge { text-align: center; }
      .bd-mring {
        position: relative; width: 64px; height: 64px; border-radius: 50%;
        margin: 0 auto 7px;
        display: flex; align-items: center; justify-content: center;
      }
      .bd-mico { font-size: 28px; line-height: 1; display: block; }
      .bd-mbadge.earned .bd-mring {
        background: linear-gradient(145deg, #F6C551, #E0992B);
        box-shadow: 0 5px 14px rgba(224,153,43,.4);
      }
      .bd-mbadge.locked .bd-mring { background: #EEF1F5; filter: grayscale(1); opacity: .7; }

      /* 獲得チェック / ロックアイコン */
      .bd-check, .bd-lock {
        position: absolute; right: -2px; bottom: -2px;
        width: 21px; height: 21px; border-radius: 50%;
        display: flex; align-items: center; justify-content: center;
        font-size: 11px; border: 2px solid #fff;
      }
      .bd-check { background: #1F6F5C; color: #fff; font-weight: 800; }
      .bd-lock  { background: #AEB6C2; color: #fff; font-size: 10px; }

      .bd-mname { font-size: 11.5px; font-weight: 700; line-height: 1.3; }
      .bd-mbadge.locked .bd-mname { color: #9AA3AF; }
      .bd-mcond { font-size: 10px; color: var(--ink-400,#9CA3AF); margin-top: 2px; line-height: 1.4; }
      .bd-mbadge.earned .bd-mcond { color: #1F6F5C; font-weight: 700; }

      /* 注記 */
      .bd-note {
        font-size: 11px; color: var(--ink-400,#9CA3AF);
        margin: 22px 0 0; line-height: 1.7;
      }

      /* ── レスポンシブ ── */
      @media(max-width: 768px){
        .bd-wrap { padding: 20px 16px 100px; }
        .bd-h1   { font-size: 20px; }
        .bd-cgrid { gap: 16px 4px; }
      }
      @media(max-width: 360px){
        .bd-cgrid  { gap: 12px 2px; }
        .bd-cname  { font-size: 10.5px; }
        .bd-cprog  { font-size: 10px; }
        .bd-mname  { font-size: 11px; }
        .bd-mcond  { font-size: 9.5px; }
      }
    `}</style>
  );
}

window.BadgesPage = BadgesPage;
