/* Page 1: Dashboard */

function Dashboard({ 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 pct          = totalSectors > 0 ? Math.round(doneSectors / totalSectors * 100) : 0;

  // 続きから学習するレッスンを探す
  let continueChapter = chapters[0];
  let continueLesson  = chapters[0].lessons[0];
  outer: for (const ch of chapters) {
    const st = chapterStatus(ch, completed);
    if (st.status === "done") continue;
    if (st.status === "locked" && ch.id > 1) break;
    continueChapter = ch;
    for (const l of ch.lessons) {
      if (!completed.includes(l.slug)) { continueLesson = l; break outer; }
    }
  }

  return (
    <main className="content">
      {/* Hero */}
      <section className="hero">
        <div className="hero-text">
          <div className="hero-eyebrow"><span className="dot-pulse"></span>毎日5分から、無理なく投資を学ぼう</div>
          <h1 className="hero-title">
            「お金の話」、<br />
            <span className="hl">株次郎</span>とはじめませんか？
          </h1>
          <p className="hero-sub">難しい言葉も、株次郎が会話形式でやさしく解説。<br />読むだけで、投資の地図が頭に入ります。</p>
          <div className="hero-cta">
            <button className="btn btn-primary btn-lg"
              onClick={() => nav.goLesson(continueLesson.slug, continueChapter.id)}>
              ▶ 続きから学習する
            </button>
            <button className="btn btn-ghost btn-lg" onClick={() => nav.goChapter(1)}>
              コース一覧を見る
            </button>
          </div>
          <div className="hero-meta">
            <div><b className="mono">{doneSectors}</b>/{totalSectors} セクター完了</div>
            <div className="dot-sep" />
            <div>全<b className="mono">{chapters.length}</b>チャプター</div>
          </div>
        </div>
        <div className="hero-art">
          <div className="hero-glow"></div>
          <Mascot size={220} mood="wink" />
          <div className="speech">
            <span>こんにちは！<br />今日も一緒に学ぼう 📈</span>
          </div>
          <div className="float-coin c1">¥</div>
          <div className="float-coin c2">$</div>
          <div className="float-coin c3">€</div>
        </div>
      </section>

      {/* 進捗カード */}
      <section className="dash-grid">
        <div className="card progress-card">
          <div className="row jcsb aic">
            <div>
              <div className="muted" style={{ fontSize: 13, fontWeight: 600 }}>基礎コース 全{chapters.length}チャプター</div>
              <div style={{ fontSize: 24, fontWeight: 800, marginTop: 4 }}>あなたの学習進捗</div>
            </div>
            <div className="ring">
              <svg width="88" height="88" viewBox="0 0 88 88">
                <circle cx="44" cy="44" r="38" fill="none" stroke="#ECEFF7" strokeWidth="8" />
                <circle cx="44" cy="44" r="38" fill="none" stroke="url(#g)" strokeWidth="8"
                  strokeLinecap="round" strokeDasharray={`${pct * 2.388} 240`} transform="rotate(-90 44 44)" />
                <defs>
                  <linearGradient id="g" x1="0" x2="1">
                    <stop offset="0" stopColor="#2D4FB8" /><stop offset="1" stopColor="#F5A623" />
                  </linearGradient>
                </defs>
              </svg>
              <div className="ring-pct"><span className="mono">{pct}</span><span className="ring-unit">%</span></div>
            </div>
          </div>
          <div className="progress" style={{ marginTop: 18 }}>
            <div className="progress-fill gold" style={{ width: `${pct}%` }} />
          </div>
          <div className="chips">
            <span className="tag tag-green">✓ 完了 {chapters.filter(c => chapterStatus(c, completed).status === "done").length}</span>
            <span className="tag tag-gold">学習中 {chapters.filter(c => chapterStatus(c, completed).status === "active").length}</span>
            <span className="tag tag-gray">🔒 ロック {chapters.filter(c => chapterStatus(c, completed).status === "locked" && c.id > 1).length}</span>
          </div>
        </div>

        <div className="card badge-card">
          <div className="bc-head">
            <div className="muted" style={{ fontSize: 13, fontWeight: 600 }}>達成バッジ</div>
            <div style={{ fontSize: 18, fontWeight: 800 }}>
              {Math.min(3, Math.floor(doneSectors / 3))} 個 獲得中
            </div>
          </div>
          <div className="badges">
            <Badge label="初学習"   emoji="🌱" earned={doneSectors >= 1} />
            <Badge label="3セクター" emoji="🔥" earned={doneSectors >= 3} />
            <Badge label="はじめに完了" emoji="🎯" earned={(() => { const c = chapters.find(ch => ch.prefix === 'hajimeni'); return c && chapterStatus(c, completed).status === "done"; })()} />
            <Badge label="目標設定"  emoji="💹" earned={(() => { const c = chapters.find(ch => ch.prefix === 'mokuhyo');  return c && chapterStatus(c, completed).status === "done"; })()} />
            <Badge label="戦略マスター" emoji="🧭" earned={(() => { const c = chapters.find(ch => ch.prefix === 'senryaku'); return c && chapterStatus(c, completed).status === "done"; })()} />
          </div>
        </div>
      </section>

      {/* 続きから */}
      <section className="continue card"
        onClick={() => nav.goLesson(continueLesson.slug, continueChapter.id)}
        style={{ cursor: "pointer" }}>
        <div className="continue-thumb">
          <Mascot size={88} mood="happy" />
        </div>
        <div className="continue-body">
          <div className="muted" style={{ fontSize: 12, fontWeight: 700, letterSpacing: ".08em" }}>つづきから</div>
          <div style={{ fontSize: 20, fontWeight: 800, marginTop: 2 }}>
            {continueChapter.isIntro ? continueChapter.title : `Chapter ${continueChapter.id} ・ ${continueChapter.title}`}
          </div>
          <div className="muted" style={{ fontSize: 14, marginTop: 4 }}>{continueLesson.title}</div>
          <div className="progress" style={{ marginTop: 12, maxWidth: 360 }}>
            <div className="progress-fill" style={{ width: `${chapterStatus(continueChapter, completed).progress}%` }} />
          </div>
        </div>
        <button className="btn btn-primary">続きから ▶</button>
      </section>

      {/* チャプター一覧 */}
      <section style={{ marginTop: 36 }}>
        <div className="row jcsb aic" style={{ marginBottom: 16 }}>
          <h2 className="h2">基礎コース</h2>
          <div className="muted" style={{ fontSize: 13 }}>順番にクリアしていこう</div>
        </div>
        <div className="chapter-grid">
          {chapters.filter(ch => !ch.isBonus && !ch.isApplied).map(ch => {
            const st = chapterStatus(ch, completed);
            return <ChapterCard key={ch.id} ch={ch} st={st} onClick={() => nav.goChapter(ch.id)} />;
          })}
        </div>
        {chapters.some(ch => ch.isBonus && !ch.isApplied) && (
          <>
            <div className="bonus-divider">番外編</div>
            <div className="chapter-grid">
              {chapters.filter(ch => ch.isBonus && !ch.isApplied).map(ch => {
                const st = chapterStatus(ch, completed);
                return <ChapterCard key={ch.id} ch={ch} st={st} onClick={() => nav.goChapter(ch.id)} />;
              })}
            </div>
          </>
        )}
      </section>

      <DashStyles />
    </main>
  );
}

function Badge({ label, emoji, earned }) {
  return (
    <div className={`badge ${earned ? "earned" : ""}`} title={label}>
      <div className="badge-emoji">{emoji}</div>
      <div className="badge-label">{label}</div>
    </div>
  );
}

function ChapterCard({ ch, st, onClick }) {
  const isBonus = !!ch.isBonus;
  const isIntro = !!ch.isIntro;
  return (
    <button
      className={`chap chap-${st.status}${isBonus ? ' chap-bonus' : ''}${isIntro ? ' chap-intro' : ''}`}
      onClick={onClick}
      disabled={st.status === "locked" && ch.id > 1 && !isBonus && !isIntro}
    >
      <div className="chap-top">
        {isBonus
          ? <div className="chap-num chap-num-bonus">番外編</div>
          : isIntro
            ? <div className="chap-num chap-num-intro">まず読む</div>
            : <div className="chap-num mono">CH.{String(ch.id).padStart(2, "0")}</div>
        }
        {st.status === "done"   && <span className="tag tag-green">✓ 完了</span>}
        {st.status === "active" && !isIntro && <span className="tag tag-gold">学習中</span>}
        {st.status === "active" && isIntro && st.done === 0 && <span className="tag tag-free">無料公開</span>}
        {st.status === "locked" && ch.id > 1 && !isBonus && !isIntro && <span className="tag tag-gray">🔒 ロック</span>}
        {isBonus && st.status !== "done" && <span className="tag tag-free">無料公開</span>}
      </div>
      <div className="chap-emoji">{ch.icon}</div>
      <div className="chap-title">{ch.title}</div>
      <div className="chap-sub muted">{ch.subtitle}</div>
      <div className="chap-foot">
        <div className="muted mono" style={{ fontSize: 11 }}>{ch.sectorCount} セクター</div>
        <div className="progress" style={{ flex: 1, height: 6 }}>
          <div className={`progress-fill ${st.status === "done" ? "green" : "gold"}`} style={{ width: `${st.progress}%` }} />
        </div>
        <div className="mono" style={{ fontSize: 11, fontWeight: 700 }}>{st.progress}%</div>
      </div>
    </button>
  );
}

function DashStyles() {
  return <style>{`
    .hero {
      position: relative; display: grid; grid-template-columns: 1.2fr 1fr;
      gap: 24px; align-items: center;
      background: linear-gradient(135deg, #1E3A8A 0%, #2D4FB8 60%, #3B66D9 100%);
      border-radius: var(--radius-xl); padding: 40px 44px;
      color: white; overflow: hidden;
      box-shadow: 0 20px 50px rgba(30,58,138,.25);
    }
    .hero::before {
      content:""; position:absolute; inset:0; pointer-events:none;
      background-image: radial-gradient(circle at 20% 20%,rgba(255,255,255,.1),transparent 40%),
                        radial-gradient(circle at 80% 100%,rgba(245,166,35,.18),transparent 50%);
    }
    .hero::after {
      content:""; position:absolute; inset:0;
      background-image: radial-gradient(circle,rgba(255,255,255,.06) 1px,transparent 1.5px);
      background-size: 22px 22px; opacity:.5; pointer-events:none;
    }
    .hero-eyebrow {
      display:inline-flex; align-items:center; gap:8px;
      background:rgba(255,255,255,.14); padding:6px 14px; border-radius:999px;
      font-size:12px; font-weight:600; backdrop-filter:blur(6px);
    }
    .dot-pulse { width:8px;height:8px;border-radius:50%;background:#10B981;
      box-shadow:0 0 0 0 rgba(16,185,129,.7); animation:pulse 1.6s infinite; }
    @keyframes pulse{0%{box-shadow:0 0 0 0 rgba(16,185,129,.7)}70%{box-shadow:0 0 0 10px rgba(16,185,129,0)}100%{box-shadow:0 0 0 0 rgba(16,185,129,0)}}
    .hero-title { font-size:38px; font-weight:800; line-height:1.3; margin:16px 0 12px; }
    .hero-title .hl { background:linear-gradient(90deg,#F5A623,#FFC15C);
      -webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text; }
    .hero-sub { font-size:15px; line-height:1.8; opacity:.88; margin-bottom:24px; }
    .hero-cta { display:flex; gap:12px; flex-wrap:wrap; }
    .hero-cta .btn-ghost { background:rgba(255,255,255,.12);color:white;border-color:rgba(255,255,255,.3); }
    .hero-cta .btn-ghost:hover { background:rgba(255,255,255,.2); }
    .hero-meta { display:flex;align-items:center;gap:14px;margin-top:20px;font-size:13px;opacity:.8; }
    .dot-sep { width:4px;height:4px;border-radius:50%;background:rgba(255,255,255,.4); }

    .hero-art { position:relative;display:flex;justify-content:center;align-items:center;min-height:280px; }
    .hero-art .mascot {
      position:relative;z-index:2;
      background:radial-gradient(circle at 50% 55%,#FFFFFF 0%,#FFF7E6 55%,rgba(255,247,230,0) 72%);
      border-radius:50%;
      filter:drop-shadow(0 18px 28px rgba(0,0,0,.35)) drop-shadow(0 0 12px rgba(255,255,255,.25));
    }
    .hero-glow { position:absolute;width:320px;height:320px;
      background:radial-gradient(circle,rgba(245,166,35,.55) 0%,rgba(255,193,92,.25) 35%,transparent 65%);
      filter:blur(18px);z-index:0; }
    .hero-art::before { content:"";position:absolute;width:240px;height:240px;
      background:radial-gradient(circle,#FFFFFF 0%,rgba(255,255,255,.5) 40%,transparent 70%);
      filter:blur(2px);z-index:1; }
    .hero-art > .mascot { animation:bob 3s ease-in-out infinite; }
    @keyframes bob{0%,100%{transform:translateY(0)}50%{transform:translateY(-8px)}}
    .speech { position:absolute;top:12px;right:0;z-index:2;
      background:white;color:var(--ink-900);padding:10px 14px;border-radius:14px;
      font-size:13px;font-weight:600;line-height:1.4;box-shadow:var(--shadow-md); }
    .speech::after { content:"";position:absolute;bottom:-8px;left:24px;
      border:8px solid transparent;border-top-color:white;border-bottom:0; }
    .float-coin { position:absolute;width:28px;height:28px;border-radius:50%;
      background:linear-gradient(135deg,#F5A623,#FFC15C);color:var(--navy-900);
      font-weight:800;font-family:var(--font-en);display:grid;place-items:center;
      font-size:14px;box-shadow:0 4px 10px rgba(245,166,35,.45);animation:float 4s ease-in-out infinite; }
    .float-coin.c1{top:60px;left:20px;animation-delay:0s}
    .float-coin.c2{bottom:70px;right:30px;animation-delay:1.2s}
    .float-coin.c3{top:140px;right:80px;animation-delay:2.4s;width:22px;height:22px;font-size:12px}
    @keyframes float{0%,100%{transform:translateY(0)}50%{transform:translateY(-12px)}}

    .dash-grid { display:grid;grid-template-columns:1.4fr 1fr;gap:20px;margin-top:28px; }
    .progress-card { padding:24px; }
    .ring { position:relative; }
    .ring-pct {
      position:absolute;inset:0;
      display:flex;align-items:center;justify-content:center;
      font-weight:800;line-height:1;gap:1px;
    }
    .ring-pct .mono { font-size:22px; }
    .ring-pct .ring-unit { font-size:14px; align-self:flex-end; margin-bottom:3px; }
    .chips { display:flex;gap:8px;margin-top:14px;flex-wrap:wrap; }
    .badge-card { padding:24px; }
    .bc-head { margin-bottom:14px; }
    .badges { display:flex;gap:10px;flex-wrap:wrap; }
    .badge { width:72px;padding:12px 8px;text-align:center;background:var(--ink-50);border-radius:14px;opacity:.5;filter:grayscale(.6); }
    .badge.earned { background:var(--gold-100);opacity:1;filter:none; }
    .badge-emoji { font-size:26px; }
    .badge-label { font-size:10px;font-weight:700;margin-top:4px;color:var(--ink-700); }
    .badge.earned .badge-label { color:var(--gold-600); }

    .continue { display:grid;grid-template-columns:auto 1fr auto;gap:20px;align-items:center;
      padding:18px 24px;margin-top:24px;
      background:linear-gradient(135deg,#FFF7E6,#FFFFFF 60%);border:1px solid var(--gold-100); }
    .continue:hover { transform:translateY(-2px);box-shadow:var(--shadow-md); }
    .continue-thumb { width:88px;height:88px;background:var(--navy-50);border-radius:16px;display:grid;place-items:center; }
    .h2 { font-size:22px;font-weight:800;margin:0; }
    .chapter-grid { display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:14px; }
    .chap { text-align:left;padding:18px;border-radius:var(--radius-lg);
      background:white;border:1px solid var(--ink-100);
      transition:transform .15s,box-shadow .15s,border-color .15s;
      display:flex;flex-direction:column;gap:8px;min-height:200px;position:relative; }
    .chap:not(:disabled):hover{transform:translateY(-3px);box-shadow:var(--shadow-md);border-color:var(--navy-100)}
    .chap-top{display:flex;justify-content:space-between;align-items:center}
    .chap-num{font-size:11px;font-weight:800;letter-spacing:.12em;color:var(--ink-500)}
    .chap-emoji{font-size:36px;line-height:1;margin:4px 0}
    .chap-title{font-size:17px;font-weight:800}
    .chap-sub{font-size:12px;line-height:1.5}
    .chap-foot{display:flex;align-items:center;gap:8px;margin-top:auto;padding-top:12px}
    .chap-active{border-color:var(--gold-400);background:linear-gradient(180deg,#FFF7E6,white 70%);box-shadow:0 4px 0 var(--gold-100)}
    .chap-done{background:linear-gradient(180deg,#F0FDF4,white 70%);border-color:var(--green-100)}
    .chap-locked{opacity:.55;cursor:not-allowed;background:var(--ink-50)}
    .chap-bonus{border-color:rgba(21,128,61,.22);background:linear-gradient(180deg,#f0fdf4,white 70%)}
    .chap-bonus:not(:disabled):hover{border-color:rgba(21,128,61,.45) !important}
    .chap-num-bonus{font-size:10px;font-weight:800;letter-spacing:.06em;color:var(--green-700,#15803d);background:var(--green-100,#dcfce7);padding:2px 8px;border-radius:99px}
    .tag-free{background:var(--green-100,#dcfce7);color:var(--green-700,#15803d)}
    .bonus-divider{margin:28px 0 14px;text-align:center;font-size:11px;font-weight:700;letter-spacing:.18em;color:var(--ink-400);display:flex;align-items:center;gap:12px}
    .bonus-divider::before,.bonus-divider::after{content:"";flex:1;height:1px;background:var(--ink-100)}
    @media(max-width:880px){
      .hero{grid-template-columns:1fr;padding:28px 22px;text-align:center}
      .hero-cta,.hero-meta{justify-content:center}
      .hero-title{font-size:28px}
      .hero-art{min-height:200px}
      .dash-grid{grid-template-columns:1fr}
      .continue{grid-template-columns:1fr;text-align:center}
      .continue .btn{width:100%}
    }
    @media(max-width:768px){
      .hero{padding:20px 16px;border-radius:16px}
      .hero-title{font-size:24px;line-height:1.3}
      .hero-sub{font-size:13px}
      .hero-art{min-height:160px}
      .hero-art .mascot{max-width:140px}
      .chapter-grid{grid-template-columns:1fr}
      .chap{min-height:auto;padding:14px}
      .chap-emoji{font-size:28px}
      .chap-title{font-size:15px}
      .continue-thumb{width:64px;height:64px}
    }
    @media(max-width:480px){
      .hero-title{font-size:20px}
      .btn-lg{padding:12px 20px;font-size:13px}
    }
  `}</style>;
}

window.Dashboard = Dashboard;
