// 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>
  );
}

Object.assign(window, { HomePage, ManseryeokPage, CheonganPage, BlogListPage, PostDetailPage });
