// pages.jsx — 페이지별 컴포넌트

const SD = window.SajuData;

// ─────────────────────────────────────────────
// 홈 — 오늘의 일주 + 오늘의 블로그 글
// ─────────────────────────────────────────────
function HomePage({ setRoute }) {
  const todayP = useMemo(() => {
    const t = Saju.todayPillar();
    return Saju.pillarInfo(t.stem, t.branch);
  }, []);
  const today = new Date();
  const post = BlogPosts[0];
  const otherPosts = BlogPosts.slice(1, 4);
  const todayInfo = SD.CHEONGAN_INFO[todayP.stem];

  return (
    <div>
      {/* 헤로 — 오늘의 글 + 오늘의 일진 */}
      <section style={{ padding: '64px 0 24px' }}>
        <div className="container" style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 56, alignItems: 'start' }}>
          {/* 오늘의 글 */}
          <article>
            <div className="eyebrow-cjk" style={{ marginBottom: 18 }}>오늘의 글 · 今日之文</div>
            <h1 className="display" style={{ fontSize: 56, fontWeight: 600, lineHeight: 1.15, letterSpacing: '-0.015em', margin: '0 0 18px', textWrap: 'balance' }}>
              {post.title}
            </h1>
            <p style={{ fontSize: 19, color: 'var(--ink-3)', lineHeight: 1.55, margin: '0 0 28px', textWrap: 'pretty', maxWidth: 620 }}>
              {post.subtitle}
            </p>
            <div style={{ display: 'flex', gap: 16, alignItems: 'center', marginBottom: 32 }}>
              <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>{fmtDate(post.date)}</span>
              <span style={{ fontSize: 13, color: 'var(--ink-mute)' }}>·</span>
              <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>{post.readMin}분 읽기</span>
              <span className="pc-tag" style={{ marginLeft: 8 }}>{post.tag}</span>
            </div>
            <button className="btn btn-lg" onClick={() => setRoute({ name: 'post', id: post.id })}>
              읽기 →
            </button>
          </article>

          {/* 오늘의 일진 — 작은 카드 */}
          <aside style={{ borderLeft: '1px solid var(--line-soft)', paddingLeft: 32 }}>
            <div className="eyebrow-cjk" style={{ marginBottom: 12 }}>오늘의 일진 · 日辰</div>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 18 }}>{fmtDate(today)}</div>
            <div className={'glyph-lg ' + elClass(todayP.stemElement)} style={{ display: 'flex', alignItems: 'baseline', gap: 2 }}>
              <span>{todayP.stemHJ}</span>
              <span style={{ opacity: 0.6 }}>{todayP.branchHJ}</span>
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, marginTop: 10, color: 'var(--ink-2)' }}>
              {todayP.label} 일주
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4, letterSpacing: '0.06em' }}>
              {todayP.stem}({todayP.stemElement}{todayP.stemYY}) · {todayP.branch}({todayP.branchElement}{todayP.branchYY})
            </div>
            <hr style={{ border: 0, height: 1, background: 'var(--line-soft)', margin: '22px 0' }} />
            <div style={{ fontSize: 13, lineHeight: 1.65, color: 'var(--ink-2)', textWrap: 'pretty' }}>
              {SD.ILJU_KEYWORDS[todayP.label] || todayInfo.character}
            </div>
            <button className="btn btn-ghost btn-sm" style={{ marginTop: 18 }}
                    onClick={() => setRoute({ name: 'cheongan', stem: todayP.stem })}>
              {todayP.stem}({todayInfo.hj}) 일주론 보기
            </button>
          </aside>
        </div>
      </section>

      <hr className="hr-fancy" style={{ margin: '36px 0' }} />

      {/* 더 읽기 — 최근 글 */}
      <section className="container" style={{ paddingBottom: 24 }}>
        <div className="eyebrow-cjk" style={{ marginBottom: 28 }}>지난 글 · 過去之文</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 28 }}>
          {otherPosts.map(p => (
            <article key={p.id} style={{ cursor: 'pointer' }} onClick={() => setRoute({ name: 'post', id: p.id })}>
              <div style={{ borderTop: '1px solid var(--ink)', paddingTop: 18 }}>
                <div style={{ display: 'flex', gap: 12, marginBottom: 14, fontSize: 12, color: 'var(--ink-3)' }}>
                  <span className="pc-tag">{p.tag}</span>
                  <span style={{ letterSpacing: '0.05em' }}>{fmtDateShort(p.date)}</span>
                </div>
                <h3 className="display" style={{ fontSize: 22, fontWeight: 600, lineHeight: 1.3, margin: '0 0 8px', textWrap: 'balance' }}>
                  {p.title}
                </h3>
                <p style={{ fontSize: 14, color: 'var(--ink-3)', lineHeight: 1.55, margin: 0, textWrap: 'pretty' }}>
                  {p.subtitle}
                </p>
              </div>
            </article>
          ))}
        </div>
      </section>

      {/* CTA */}
      <section className="container" style={{ padding: '72px 0 24px' }}>
        <div className="card" style={{ display: 'grid', gridTemplateColumns: '1fr auto', alignItems: 'center', gap: 24, background: 'var(--paper-2)' }}>
          <div>
            <div className="eyebrow-cjk" style={{ marginBottom: 8 }}>萬歲曆</div>
            <h3 className="display" style={{ fontSize: 28, margin: '0 0 6px', fontWeight: 600 }}>
              내 사주, 네 기둥으로 펼쳐 보기
            </h3>
            <p style={{ margin: 0, color: 'var(--ink-3)', fontSize: 15 }}>
              생년월일시를 입력하면 천간과 지지로 이루어진 여덟 글자가 펼쳐집니다.
            </p>
          </div>
          <button className="btn btn-lg" onClick={() => setRoute({ name: 'manse' })}>만세력 열기 →</button>
        </div>
      </section>
    </div>
  );
}

// ─────────────────────────────────────────────
// 만세력 페이지 — 입력 + 4주표
// ─────────────────────────────────────────────
function ManseryeokPage() {
  const [form, setForm] = useState({ year: 1990, month: 5, day: 22, hour: 14, minute: 30, gender: 'male' });
  const [showResult, setShowResult] = useState(true);

  const saju = useMemo(() => {
    return Saju.computeSaju(form.year, form.month, form.day, form.hour, form.minute);
  }, [form]);

  // 오행 통계
  const stats = useMemo(() => {
    const counts = { 목: 0, 화: 0, 토: 0, 금: 0, 수: 0 };
    ['year','month','day','hour'].forEach(k => {
      counts[saju[k].stemElement]++;
      counts[saju[k].branchElement]++;
    });
    return counts;
  }, [saju]);

  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));

  return (
    <div>
      <div className="page-hd">
        <div className="eyebrow-cjk">만세력 · 萬歲曆</div>
        <h1>여덟 글자로 펼치는 네 기둥</h1>
        <p>태어난 연·월·일·시를 입력하면 오른쪽부터 왼쪽으로 — 년주·월주·일주·시주가 자리 잡습니다.</p>
      </div>

      <div className="container-narrow">
        <div className="card">
          <div className="manse-form">
            <div className="field">
              <label className="label">연 年</label>
              <input className="input" type="number" value={form.year}
                     onChange={(e) => update('year', +e.target.value)} />
            </div>
            <div className="field">
              <label className="label">월 月</label>
              <input className="input" type="number" min="1" max="12" value={form.month}
                     onChange={(e) => update('month', +e.target.value)} />
            </div>
            <div className="field">
              <label className="label">일 日</label>
              <input className="input" type="number" min="1" max="31" value={form.day}
                     onChange={(e) => update('day', +e.target.value)} />
            </div>
            <div className="field">
              <label className="label">시 時</label>
              <input className="input" type="number" min="0" max="23" value={form.hour}
                     onChange={(e) => update('hour', +e.target.value)} />
            </div>
            <div className="field">
              <label className="label">분 分</label>
              <input className="input" type="number" min="0" max="59" value={form.minute}
                     onChange={(e) => update('minute', +e.target.value)} />
            </div>
            <button className="btn" onClick={() => setShowResult(true)}>펼치기 →</button>
          </div>
          <div style={{ marginTop: 14, fontSize: 12, color: 'var(--ink-mute)' }}>
            * 절기 기준 근사 계산. 정확한 자시(子時) 구분과 시간대 보정은 적용되지 않습니다.
          </div>
        </div>

        {showResult && (
          <>
            <div className="meta-row" style={{ margin: '40px 0 22px', justifyContent: 'center' }}>
              <div className="item"><span className="k">생년월일시</span>
                <span className="v">{form.year}.{String(form.month).padStart(2,'0')}.{String(form.day).padStart(2,'0')} {String(form.hour).padStart(2,'0')}:{String(form.minute).padStart(2,'0')}</span></div>
              <div className="item"><span className="k">일주</span>
                <span className="v">{saju.day.label} · {saju.day.labelHJ}</span></div>
              <div className="item"><span className="k">일간</span>
                <span className="v">{saju.day.stem}({saju.day.stemHJ}) {saju.day.stemElement}{saju.day.stemYY}</span></div>
            </div>

            <SajuTable saju={saju} />

            {/* 오행 분포 */}
            <div style={{ marginTop: 40 }}>
              <div className="eyebrow" style={{ marginBottom: 14 }}>OHAENG · 五行 분포</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12 }}>
                {Object.entries(stats).map(([el, n]) => (
                  <div key={el} className={'card ' + elBgClass(el)} style={{ padding: '20px 16px', textAlign: 'center', borderRadius: 'var(--r-md)' }}>
                    <div className={'glyph-lg ' + elClass(el)} style={{ fontSize: 48 }}>{elHJ(el)}</div>
                    <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6, letterSpacing: '0.1em' }}>{el}</div>
                    <div style={{ fontFamily: 'var(--font-num)', fontSize: 28, marginTop: 4 }}>{n}<span style={{ fontSize: 13, color: 'var(--ink-mute)' }}>/8</span></div>
                  </div>
                ))}
              </div>
            </div>

            {/* 일주 해설 */}
            <div className="card" style={{ marginTop: 32 }}>
              <div className="eyebrow-cjk" style={{ marginBottom: 12 }}>일주론 · {saju.day.label}</div>
              <h3 className="display" style={{ fontSize: 28, margin: '0 0 14px', fontWeight: 600 }}>
                나의 일주는 {saju.day.label}({saju.day.labelHJ})입니다
              </h3>
              <p style={{ fontSize: 16, lineHeight: 1.75, color: 'var(--ink-2)', margin: 0, textWrap: 'pretty' }}>
                {SD.ILJU_KEYWORDS[saju.day.label]}
              </p>
              <hr style={{ border: 0, height: 1, background: 'var(--line-soft)', margin: '24px 0' }} />
              <div style={{ fontSize: 15, lineHeight: 1.75, color: 'var(--ink-2)' }}>
                <strong style={{ fontFamily: 'var(--font-display)', fontWeight: 600 }}>일간 {saju.day.stem}({saju.day.stemHJ}) — </strong>
                {SD.CHEONGAN_INFO[saju.day.stem].character}
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────
// 천간·일주 — 천간 10개 그리드 → 클릭하면 그 천간의 일주 6개
// ─────────────────────────────────────────────
function CheonganPage({ initialStem, setRoute }) {
  const [stem, setStem] = useState(initialStem || '갑');
  const info = SD.CHEONGAN_INFO[stem];
  const stemIdx = Saju.STEMS.indexOf(stem);
  const ilju = useMemo(() => Saju.iljuByStem(stemIdx), [stemIdx]);

  return (
    <div>
      <div className="page-hd">
        <div className="eyebrow-cjk">천간·일주 · 天干日柱</div>
        <h1>하늘의 열 글자, 그리고 그 일주들</h1>
        <p>천간 한 글자를 누르면 그 천간을 일간으로 하는 여섯 개의 일주가 펼쳐집니다.</p>
      </div>

      <div className="container">
        {/* 10개 그리드 */}
        <div className="cheongan-grid">
          {Saju.STEMS.map(s => (
            <CheonganTile key={s} stem={s} info={SD.CHEONGAN_INFO[s]}
                          active={stem === s} onClick={() => setStem(s)} />
          ))}
        </div>

        {/* 선택된 천간 상세 */}
        <div style={{ marginTop: 56, display: 'grid', gridTemplateColumns: '380px 1fr', gap: 56, alignItems: 'start' }}>
          <div>
            <div className="eyebrow-cjk" style={{ marginBottom: 16 }}>선택 · 選</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 18 }}>
              <div className={'glyph-xl ' + elClass(info.element)}>{info.hj}</div>
              <div>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 36, fontWeight: 500 }}>{stem}</div>
                <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4, letterSpacing: '0.1em' }}>
                  {info.element}({elHJ(info.element)}) · {info.yy}
                </div>
              </div>
            </div>
            <div style={{ marginTop: 22, padding: 16, background: 'var(--paper-2)', borderRadius: 'var(--r-md)' }}>
              <div className="eyebrow" style={{ marginBottom: 8 }}>SYMBOL · 物象</div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500 }}>{info.symbol}</div>
              <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4 }}>{info.symbolDetail}</div>
            </div>
            <div style={{ marginTop: 18 }}>
              <div className="eyebrow" style={{ marginBottom: 10 }}>KEYWORDS · 性</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {info.keywords.map(k => (
                  <span key={k} style={{
                    fontSize: 13, padding: '5px 11px',
                    border: '1px solid var(--line)',
                    borderRadius: 999,
                    color: 'var(--ink-2)',
                  }}>{k}</span>
                ))}
              </div>
            </div>
          </div>

          <div>
            <p style={{ fontSize: 17, lineHeight: 1.8, color: 'var(--ink-2)', margin: '0 0 24px', textWrap: 'pretty' }}>
              {info.character}
            </p>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <div style={{ padding: 18, borderLeft: '2px solid var(--wood)', background: 'var(--paper-2)', borderRadius: '0 var(--r-md) var(--r-md) 0' }}>
                <div className="eyebrow" style={{ marginBottom: 6 }}>STRENGTH · 長</div>
                <div style={{ fontSize: 14, color: 'var(--ink-2)' }}>{info.strength}</div>
              </div>
              <div style={{ padding: 18, borderLeft: '2px solid var(--fire)', background: 'var(--paper-2)', borderRadius: '0 var(--r-md) var(--r-md) 0' }}>
                <div className="eyebrow" style={{ marginBottom: 6 }}>WEAKNESS · 短</div>
                <div style={{ fontSize: 14, color: 'var(--ink-2)' }}>{info.weakness}</div>
              </div>
            </div>
          </div>
        </div>

        <hr className="hr-fancy" />

        {/* 6개 일주 */}
        <div>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 22 }}>
            <div>
              <div className="eyebrow-cjk" style={{ marginBottom: 6 }}>{stem}({info.hj}) 일주 · 六十甲子 中</div>
              <h2 className="display" style={{ fontSize: 30, fontWeight: 600, margin: 0 }}>
                {stem}이 일간인 여섯 개의 일주
              </h2>
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>총 6개</div>
          </div>
          <div className="ilju-grid">
            {ilju.map(p => (
              <IljuCard key={p.label} pillar={p} keyword={SD.ILJU_KEYWORDS[p.label]} />
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────
// 블로그 목록
// ─────────────────────────────────────────────
function BlogListPage({ setRoute }) {
  return (
    <div>
      <div className="page-hd">
        <div className="eyebrow-cjk">글 · 日誌</div>
        <h1>매일 한 편씩 쌓이는 사주 이야기</h1>
        <p>입문자를 위한 짧은 글들. 매일 한 편씩 천천히 읽어 보세요.</p>
      </div>
      <div className="container-narrow">
        {BlogPosts.map(p => (
          <article key={p.id} className="post-card" onClick={() => setRoute({ name: 'post', id: p.id })}>
            <div className="pc-body">
              <div className="pc-meta">
                <span className="pc-tag">{p.tag}</span>
                <span>{fmtDate(p.date)}</span>
                <span>·</span>
                <span>{p.readMin}분</span>
              </div>
              <h2 className="pc-title">{p.title}</h2>
              <p className="pc-sub">{p.subtitle}</p>
            </div>
            <div className="pc-hero">{p.title.match(/[\u4e00-\u9fff]/g)?.[0] || '命'}</div>
          </article>
        ))}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────
// 블로그 상세
// ─────────────────────────────────────────────
function PostDetailPage({ id, setRoute }) {
  const post = BlogPosts.find(p => p.id === id) || BlogPosts[0];
  return (
    <div className="post-detail">
      <div className="container-narrow">
        <button className="btn btn-ghost btn-sm" onClick={() => setRoute({ name: 'blog' })}>← 글 목록으로</button>
        <div className="pc-meta" style={{ display: 'flex', gap: 14, alignItems: 'center', margin: '36px 0 14px', fontSize: 13, color: 'var(--ink-3)' }}>
          <span className="pc-tag">{post.tag}</span>
          <span>{fmtDate(post.date)}</span>
          <span>·</span>
          <span>{post.readMin}분 읽기</span>
        </div>
        <h1>{post.title}</h1>
        <div className="sub">{post.subtitle}</div>
        <div style={{
          background: 'var(--paper-2)',
          padding: '20px 24px',
          borderLeft: '3px solid var(--accent)',
          borderRadius: '0 var(--r-md) var(--r-md) 0',
          fontFamily: 'var(--font-display)',
          fontSize: 16,
          color: 'var(--ink-2)',
          marginBottom: 40,
          textWrap: 'pretty',
        }}>{post.hero}</div>

        <div className="body">
          {post.body.map((b, i) => {
            if (b.type === 'h') return <h2 key={i}>{b.text}</h2>;
            if (b.type === 'q') return <blockquote key={i}>{b.text}</blockquote>;
            return <p key={i}>{b.text}</p>;
          })}
        </div>

        <hr className="hr-fancy" />
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <div className="seal">紫</div>
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 16, color: 'var(--ink)' }}>{post.author}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>Purplica · 매일 한 편</div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────
// 오행 — 5원소 그리드 개요
// ─────────────────────────────────────────────
function OhengPage({ setRoute }) {
  const elements = ['목', '화', '토', '금', '수'];
  return (
    <div>
      <div className="page-hd">
        <div className="eyebrow-cjk">오행 · 五行</div>
        <h1>다섯 가지 기운의 세계</h1>
        <p>목(木)·화(火)·토(土)·금(金)·수(水) — 자연의 다섯 가지 에너지가 만물을 순환시킵니다.</p>
      </div>
      <div className="container">
        <div className="oheng-grid">
          {elements.map(el => (
            <OhengTile key={el} element={el} info={SD.OHENG_INFO[el]}
                       onClick={() => setRoute({ name: 'oheng-detail', element: el })} />
          ))}
        </div>

        <AdBanner />

        {/* 상생상극 간단 소개 */}
        <div className="card" style={{ marginTop: 32, padding: '32px 28px' }}>
          <div className="eyebrow-cjk" style={{ marginBottom: 14 }}>상생·상극 · 生剋</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32 }}>
            <div>
              <h3 className="display" style={{ fontSize: 20, margin: '0 0 10px', fontWeight: 600 }}>상생(相生) — 살리는 관계</h3>
              <p style={{ fontSize: 14, lineHeight: 1.75, color: 'var(--ink-2)', margin: 0 }}>
                목→화→토→금→수→목. 나무가 불을 살리고, 불이 흙을 만들고, 흙이 쇠를 품고, 쇠가 물을 모으고, 물이 나무를 키웁니다.
              </p>
            </div>
            <div>
              <h3 className="display" style={{ fontSize: 20, margin: '0 0 10px', fontWeight: 600 }}>상극(相剋) — 다스리는 관계</h3>
              <p style={{ fontSize: 14, lineHeight: 1.75, color: 'var(--ink-2)', margin: 0 }}>
                목→토→수→화→금→목. 나무가 흙을 뚫고, 흙이 물을 막고, 물이 불을 끄고, 불이 쇠를 녹이고, 쇠가 나무를 벱니다.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────
// 오행 상세 — 단일 오행 + 해당 천간 2개 카드
// ─────────────────────────────────────────────
function OhengDetailPage({ element, setRoute }) {
  const info = SD.OHENG_INFO[element];
  if (!info) return <div className="empty">데이터를 찾을 수 없습니다.</div>;

  return (
    <div>
      <div className="container" style={{ paddingTop: 40 }}>
        <Breadcrumb items={[
          { label: '오행(五行)', onClick: () => setRoute({ name: 'oheng' }) },
          { label: `${info.nameKo}(${info.hj})` },
        ]} />

        {/* 오행 히어로 */}
        <div className="cheongan-detail-body">
          <div className="cd-left">
            <div className={'cd-glyph ' + elClass(element)}>{info.hj}</div>
            <div style={{ marginTop: 12, fontSize: 14, color: 'var(--ink-3)' }}>
              {info.season} · {info.direction}
            </div>
            <div style={{ marginTop: 6, fontSize: 13, color: 'var(--ink-mute)' }}>
              {info.organ}
            </div>
            <div style={{ marginTop: 12, display: 'flex', justifyContent: 'center', flexWrap: 'wrap', gap: 6 }}>
              {info.keywords.map(k => (
                <span key={k} style={{ fontSize: 12, padding: '4px 10px', border: '1px solid var(--line)', borderRadius: 999, color: 'var(--ink-2)' }}>{k}</span>
              ))}
            </div>
          </div>
          <div className="cd-right">
            <h3>{info.virtue}</h3>
            <p>{info.character}</p>
            <h3>과다(過多)할 때</h3>
            <p>{info.excess}</p>
            <h3>결핍(缺乏)할 때</h3>
            <p>{info.deficiency}</p>
            <h3>상생·상극 관계</h3>
            <p>
              <strong>나를 살리는 오행:</strong> {info.generatedBy}({elHJ(info.generatedBy)})생{info.nameKo} &nbsp;|&nbsp;
              <strong>내가 살리는 오행:</strong> {info.nameKo}생{info.generates}({elHJ(info.generates)})<br />
              <strong>나를 다스리는 오행:</strong> {info.overcomeBy}({elHJ(info.overcomeBy)})극{info.nameKo} &nbsp;|&nbsp;
              <strong>내가 다스리는 오행:</strong> {info.nameKo}극{info.overcomes}({elHJ(info.overcomes)})
            </p>
          </div>
        </div>

        <AdBanner />

        {/* 이 오행의 천간 — 양/음 2개 */}
        <div style={{ marginTop: 40 }}>
          <div className="eyebrow-cjk" style={{ marginBottom: 16 }}>
            {info.nameKo}({info.hj})의 천간 · 天干
          </div>
          <h2 className="display" style={{ fontSize: 28, fontWeight: 600, margin: '0 0 20px' }}>
            양{info.nameKo}과 음{info.nameKo}, 두 가지 표현
          </h2>
          <div className="stem-cards">
            {info.stems.map(s => {
              const si = SD.CHEONGAN_INFO[s];
              return (
                <div key={s} className={'stem-card ' + elBgClass(element)}
                     onClick={() => setRoute({ name: 'cheongan-detail', stem: s })}>
                  <div className={'sc-hj ' + elClass(element)}>{si.hj}</div>
                  <div className="sc-name">{s}({si.yy}{info.nameKo}) — {si.symbol}</div>
                  <div className="sc-symbol">{si.symbolDetail}</div>
                  <div className="sc-keywords">
                    {si.keywords.map(k => <span key={k} className="sc-kw">{k}</span>)}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────
// 천간 상세 — 단일 천간 + 성별 토글 + 일주 pill
// ─────────────────────────────────────────────
function CheonganDetailPage({ stem, gender, setGender, setRoute }) {
  const info = SD.CHEONGAN_INFO[stem];
  if (!info) return <div className="empty">데이터를 찾을 수 없습니다.</div>;

  const stemIdx = Saju.STEMS.indexOf(stem);
  const ilju = useMemo(() => Saju.iljuByStem(stemIdx), [stemIdx]);
  const ohengInfo = SD.OHENG_INFO[info.element];
  const genderData = SD.GENDER_INTERP[stem]?.[gender];

  return (
    <div>
      <div className="container" style={{ paddingTop: 40 }}>
        {/* Top Bar: Breadcrumb + Gender Toggle */}
        <div className="detail-top-bar">
          <Breadcrumb items={[
            { label: '오행(五行)', onClick: () => setRoute({ name: 'oheng' }) },
            { label: `${info.element}(${elHJ(info.element)})`, onClick: () => setRoute({ name: 'oheng-detail', element: info.element }) },
            { label: `${stem}(${info.hj})` },
          ]} />
          <GenderToggle gender={gender} setGender={setGender} />
        </div>

        {/* 일주 Pill Bar */}
        <div style={{ marginBottom: 32 }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>
            {stem}({info.hj})의 일주 · DAY PILLARS
          </div>
          <IljuPillBar stemIdx={stemIdx} activeLabel="" setRoute={setRoute} />
        </div>

        {/* 천간 상세 본문 */}
        <div className="cheongan-detail-body">
          <div className="cd-left">
            <div className={'cd-glyph ' + elClass(info.element)}>{info.hj}</div>
            <div style={{ marginTop: 12 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 32, fontWeight: 500 }}>{stem}</div>
              <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4, letterSpacing: '0.1em' }}>
                {info.element}({elHJ(info.element)}) · {info.yy} · {info.season}
              </div>
            </div>
            <div style={{ marginTop: 22, padding: 16, background: 'var(--paper-2)', borderRadius: 'var(--r-md)' }}>
              <div className="eyebrow" style={{ marginBottom: 8 }}>SYMBOL · 物象</div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 500 }}>{info.symbol}</div>
              <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4 }}>{info.symbolDetail}</div>
            </div>
            <div style={{ marginTop: 18 }}>
              <div className="eyebrow" style={{ marginBottom: 10 }}>KEYWORDS · 性</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, justifyContent: 'center' }}>
                {info.keywords.map(k => (
                  <span key={k} style={{ fontSize: 12, padding: '4px 10px', border: '1px solid var(--line)', borderRadius: 999, color: 'var(--ink-2)' }}>{k}</span>
                ))}
              </div>
            </div>
          </div>

          <div className="cd-right">
            <h3>성질 · 性質</h3>
            <p>{info.character}</p>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, margin: '20px 0' }}>
              <div style={{ padding: 16, borderLeft: '2px solid var(--wood)', background: 'var(--paper-2)', borderRadius: '0 var(--r-md) var(--r-md) 0' }}>
                <div className="eyebrow" style={{ marginBottom: 6 }}>STRENGTH · 長</div>
                <div style={{ fontSize: 14, color: 'var(--ink-2)' }}>{info.strength}</div>
              </div>
              <div style={{ padding: 16, borderLeft: '2px solid var(--fire)', background: 'var(--paper-2)', borderRadius: '0 var(--r-md) var(--r-md) 0' }}>
                <div className="eyebrow" style={{ marginBottom: 6 }}>WEAKNESS · 短</div>
                <div style={{ fontSize: 14, color: 'var(--ink-2)' }}>{info.weakness}</div>
              </div>
            </div>
          </div>
        </div>

        {/* 성별 해석 섹션 */}
        <div className="gender-section">
          <div className="gs-title">{gender === 'male' ? '남자' : '여자'} {stem}({info.hj})의 특성</div>
          {genderData ? (
            <div style={{ fontSize: 15, lineHeight: 1.8, color: 'var(--ink-2)' }}>
              {genderData.love && <p><strong>연애·결혼:</strong> {genderData.love}</p>}
              {genderData.career && <p><strong>직업·사업:</strong> {genderData.career}</p>}
              {genderData.health && <p><strong>건강:</strong> {genderData.health}</p>}
            </div>
          ) : (
            <div className="gender-placeholder">
              성별 해석 콘텐츠를 준비 중입니다. 곧 업데이트됩니다.
            </div>
          )}
        </div>

        <AdBanner />

        {/* 하단 일주 카드 그리드 */}
        <div className="related-ilju">
          <h3>{stem}({info.hj})이 일간인 여섯 개의 일주</h3>
          <div className="ilju-grid">
            {ilju.map(p => (
              <div key={p.label} style={{ cursor: 'pointer' }}
                   onClick={() => setRoute({ name: 'ilju-detail', label: p.label })}>
                <IljuCard pillar={p} keyword={SD.ILJU_KEYWORDS[p.label]} />
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────
// 일주 상세 — 단일 일주 + 성별 토글
// ─────────────────────────────────────────────
function IljuDetailPage({ label, gender, setGender, setRoute }) {
  const stemChar = label[0];
  const branchChar = label[1];
  const stemIdx = Saju.STEMS.indexOf(stemChar);
  const branchIdx = Saju.BRANCHES.indexOf(branchChar);
  const pillar = Saju.pillarInfo(stemIdx, branchIdx);
  const stemInfo = SD.CHEONGAN_INFO[stemChar];
  const branchInfo = SD.JIJI_INFO[branchChar];
  const keyword = SD.ILJU_KEYWORDS[label];
  const genderData = SD.GENDER_INTERP[label]?.[gender];

  // 같은 천간의 다른 일주
  const siblings = useMemo(() => Saju.iljuByStem(stemIdx).filter(p => p.label !== label), [stemIdx, label]);

  if (!stemInfo) return <div className="empty">데이터를 찾을 수 없습니다.</div>;

  return (
    <div>
      <div className="container" style={{ paddingTop: 40 }}>
        {/* Top Bar */}
        <div className="detail-top-bar">
          <Breadcrumb items={[
            { label: '오행(五行)', onClick: () => setRoute({ name: 'oheng' }) },
            { label: `${stemInfo.element}(${elHJ(stemInfo.element)})`, onClick: () => setRoute({ name: 'oheng-detail', element: stemInfo.element }) },
            { label: `${stemChar}(${stemInfo.hj})`, onClick: () => setRoute({ name: 'cheongan-detail', stem: stemChar }) },
            { label: `${label}(${pillar.labelHJ})` },
          ]} />
          <GenderToggle gender={gender} setGender={setGender} />
        </div>

        {/* 일주 Pill Bar (현재 활성 표시) */}
        <div style={{ marginBottom: 32 }}>
          <IljuPillBar stemIdx={stemIdx} activeLabel={label} setRoute={setRoute} />
        </div>

        {/* 일주 히어로 */}
        <div className="cheongan-detail-body">
          <div className="cd-left">
            <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'center', gap: 4 }}>
              <span className={'cd-glyph ' + elClass(pillar.stemElement)}>{pillar.stemHJ}</span>
              <span className="cd-glyph" style={{ opacity: 0.5 }}>{pillar.branchHJ}</span>
            </div>
            <div style={{ marginTop: 12 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 500 }}>
                {label} 일주
              </div>
              <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 6, letterSpacing: '0.08em' }}>
                {pillar.stem}({pillar.stemElement}{pillar.stemYY}) · {pillar.branch}({pillar.branchElement}{pillar.branchYY})
              </div>
            </div>
            {branchInfo && (
              <div style={{ marginTop: 18, padding: 14, background: 'var(--paper-2)', borderRadius: 'var(--r-md)', fontSize: 13 }}>
                <div style={{ color: 'var(--ink-mute)', marginBottom: 4 }}>지지 · {branchChar}({branchInfo.hj})</div>
                <div style={{ color: 'var(--ink-2)' }}>{branchInfo.animal} · {branchInfo.element}({branchInfo.yy}) · {branchInfo.hour}</div>
              </div>
            )}
          </div>
          <div className="cd-right">
            <h3>일주론 · 日柱論</h3>
            <p style={{ fontSize: 17 }}>{keyword}</p>
            <h3>일간 {stemChar}({stemInfo.hj})의 성질</h3>
            <p>{stemInfo.character}</p>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, margin: '20px 0' }}>
              <div style={{ padding: 16, borderLeft: '2px solid var(--wood)', background: 'var(--paper-2)', borderRadius: '0 var(--r-md) var(--r-md) 0' }}>
                <div className="eyebrow" style={{ marginBottom: 6 }}>STRENGTH · 長</div>
                <div style={{ fontSize: 14, color: 'var(--ink-2)' }}>{stemInfo.strength}</div>
              </div>
              <div style={{ padding: 16, borderLeft: '2px solid var(--fire)', background: 'var(--paper-2)', borderRadius: '0 var(--r-md) var(--r-md) 0' }}>
                <div className="eyebrow" style={{ marginBottom: 6 }}>WEAKNESS · 短</div>
                <div style={{ fontSize: 14, color: 'var(--ink-2)' }}>{stemInfo.weakness}</div>
              </div>
            </div>
          </div>
        </div>

        {/* 성별 해석 */}
        <div className="gender-section">
          <div className="gs-title">{gender === 'male' ? '남자' : '여자'} {label}({pillar.labelHJ}) 일주의 특성</div>
          {genderData ? (
            <div style={{ fontSize: 15, lineHeight: 1.8, color: 'var(--ink-2)' }}>
              {genderData.love && <p><strong>연애·결혼:</strong> {genderData.love}</p>}
              {genderData.career && <p><strong>직업·사업:</strong> {genderData.career}</p>}
              {genderData.health && <p><strong>건강:</strong> {genderData.health}</p>}
            </div>
          ) : (
            <div className="gender-placeholder">
              성별 해석 콘텐츠를 준비 중입니다. 곧 업데이트됩니다.
            </div>
          )}
        </div>

        <AdBanner />

        {/* 관련 일주 */}
        {siblings.length > 0 && (
          <div className="related-ilju">
            <h3>{stemChar}({stemInfo.hj})의 다른 일주</h3>
            <div className="ilju-grid">
              {siblings.map(p => (
                <div key={p.label} style={{ cursor: 'pointer' }}
                     onClick={() => setRoute({ name: 'ilju-detail', label: p.label })}>
                  <IljuCard pillar={p} keyword={SD.ILJU_KEYWORDS[p.label]} />
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, {
  HomePage, ManseryeokPage, CheonganPage, BlogListPage, PostDetailPage,
  OhengPage, OhengDetailPage, CheonganDetailPage, IljuDetailPage,
});
