// components.jsx — 공통 컴포넌트들

const { useState, useEffect, useMemo, useRef } = React;

// 오행 → CSS 클래스
const elClass = (el) => ({
  '목': 'el-wood', '화': 'el-fire', '토': 'el-earth', '금': 'el-metal', '수': 'el-water'
}[el] || '');
const elBgClass = (el) => ({
  '목': 'el-bg-wood', '화': 'el-bg-fire', '토': 'el-bg-earth', '금': 'el-bg-metal', '수': 'el-bg-water'
}[el] || '');
const elHJ = (el) => ({'목':'木','화':'火','토':'土','금':'金','수':'水'}[el]);

// ─── Brand mark ───
function Brand({ onClick }) {
  return (
    <div className="nav-brand" onClick={onClick} style={{ cursor: 'pointer' }}>
      <div className="mark" style={{ fontFamily: "'Cormorant Garamond', 'Noto Serif KR', serif", fontWeight: 600, fontStyle: 'italic', letterSpacing: '-0.015em', fontSize: 26 }}>
        Purplica
      </div>
      <div className="mark-cjk" style={{ fontSize: 14, letterSpacing: '0.16em', borderLeft: '1px solid var(--line)', paddingLeft: 10, color: 'var(--accent)' }}>紫微</div>
    </div>
  );
}

// ─── Nav ───
function Nav({ route, setRoute }) {
  const items = [
    { id: 'home', ko: '오늘', hj: '今日' },
    { id: 'oheng', ko: '오행', hj: '五行' },
    { id: 'manse', ko: '만세력', hj: '萬歲曆' },
    { id: 'cheongan', ko: '천간·일주', hj: '天干' },
    { id: 'blog', ko: '글', hj: '日誌' },
  ];
  const isActive = (it) => {
    if (it.id === 'oheng') return ['oheng','oheng-detail','cheongan-detail','ilju-detail'].includes(route.name);
    if (it.id === 'cheongan') return route.name === 'cheongan';
    if (it.id === 'blog') return ['blog','post'].includes(route.name);
    return route.name === it.id;
  };
  return (
    <nav className="nav">
      <div className="nav-inner">
        <Brand onClick={() => setRoute({ name: 'home' })} />
        <div className="nav-links">
          {items.map(it => (
            <a key={it.id}
               className={'nav-link ' + (isActive(it) ? 'active' : '')}
               onClick={(e) => { e.preventDefault(); setRoute({ name: it.id }); }}>
              {it.ko}<span className="cjk">{it.hj}</span>
            </a>
          ))}
        </div>
      </div>
    </nav>
  );
}

// ─── 4주표 (오른쪽부터 왼쪽 — 년·월·일·시) ───
function SajuTable({ saju }) {
  // 데이터 순서는 년→월→일→시. CSS direction: rtl이 시각 순서를 뒤집어 줌.
  const cols = [
    { key: 'year',  ko: '년주', hj: '年柱', role: 'YEAR · 시대·조상' },
    { key: 'month', ko: '월주', hj: '月柱', role: 'MONTH · 부모·환경' },
    { key: 'day',   ko: '일주', hj: '日柱', role: 'DAY · 본인·배우자' },
    { key: 'hour',  ko: '시주', hj: '時柱', role: 'HOUR · 자식·말년' },
  ];
  return (
    <div className="saju-table">
      {cols.map(c => {
        const p = saju[c.key];
        return (
          <div key={c.key} className="saju-col">
            <div className="saju-col-head">
              <div className="ko">{c.ko}</div>
              <div className="hj">{c.hj}</div>
              <div className="role">{c.role}</div>
            </div>
            <div className={'saju-cell ' + elBgClass(p.stemElement)}>
              <div className={'char-hj ' + elClass(p.stemElement)}>{p.stemHJ}</div>
              <div className="char-ko">{p.stem}({p.stemYY}{elHJ(p.stemElement)})</div>
              <div className="meta">天干 · CHEONGAN</div>
            </div>
            <div className={'saju-cell ' + elBgClass(p.branchElement)}>
              <div className={'char-hj ' + elClass(p.branchElement)}>{p.branchHJ}</div>
              <div className="char-ko">{p.branch}({p.branchYY}{elHJ(p.branchElement)})</div>
              <div className="meta">地支 · JIJI</div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ─── 천간 타일 (10개 그리드용) ───
function CheonganTile({ stem, info, active, onClick }) {
  return (
    <div className={'cheongan-tile' + (active ? ' active' : '')} onClick={onClick}>
      <div className={'hj ' + (active ? '' : elClass(info.element))}>{info.hj}</div>
      <div className="ko">{stem}({info.element}{info.yy})</div>
      <div className="meta">{info.symbol}</div>
    </div>
  );
}

// ─── 일주 카드 ───
function IljuCard({ pillar, keyword }) {
  return (
    <div className={'ilju-card ' + elBgClass(pillar.stemElement)}>
      <div className="top-meta">{pillar.stem}{pillar.branch}</div>
      <div className={'hj-pair ' + elClass(pillar.stemElement)}>
        <span>{pillar.stemHJ}</span>
        <span style={{ opacity: 0.55 }}>{pillar.branchHJ}</span>
      </div>
      <div className="ko-pair">{pillar.label} · {pillar.labelHJ}</div>
      <div className="kw">{keyword || ''}</div>
    </div>
  );
}

// ─── 날짜 포맷 ───
function fmtDate(d) {
  const dt = (d instanceof Date) ? d : new Date(d);
  const wk = ['일','월','화','수','목','금','토'][dt.getDay()];
  return `${dt.getFullYear()}년 ${dt.getMonth()+1}월 ${dt.getDate()}일 (${wk})`;
}
function fmtDateShort(d) {
  const dt = (d instanceof Date) ? d : new Date(d);
  return `${dt.getFullYear()}.${String(dt.getMonth()+1).padStart(2,'0')}.${String(dt.getDate()).padStart(2,'0')}`;
}

// ─── Footer ───
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
          <div className="seal">紫</div>
          <div>
            <div style={{ fontFamily: "'Cormorant Garamond', serif", fontStyle: 'italic', color: 'var(--ink)', fontSize: 18, fontWeight: 600 }}>Purplica <span style={{ fontFamily: 'var(--font-display)', fontStyle: 'normal', fontSize: 13, color: 'var(--accent)', marginLeft: 4, letterSpacing: '0.14em' }}>紫微</span></div>
            <div style={{ fontSize: 12, color: 'var(--ink-mute)', marginTop: 2 }}>매일 한 편의 사주 이야기 · A modern almanac of Saju</div>
          </div>
        </div>
        <div style={{ fontSize: 12 }}>© 2026 Purplica. All four pillars, gently read.</div>
      </div>
    </footer>
  );
}

// ─── 성별 토글 ───
function GenderToggle({ gender, setGender }) {
  return (
    <div className="gender-toggle">
      <button className={'gt-btn' + (gender === 'male' ? ' active' : '')}
              onClick={() => setGender('male')}>남자 ♂</button>
      <button className={'gt-btn' + (gender === 'female' ? ' active' : '')}
              onClick={() => setGender('female')}>여자 ♀</button>
    </div>
  );
}

// ─── 일주 Pill Bar (천간별 6개) ───
function IljuPillBar({ stemIdx, activeLabel, setRoute }) {
  const pillars = Saju.iljuByStem(stemIdx);
  return (
    <div className="ilju-pill-bar">
      {pillars.map(p => (
        <button key={p.label}
                className={'pill' + (activeLabel === p.label ? ' active' : '')}
                onClick={() => setRoute({ name: 'ilju-detail', label: p.label })}>
          <span className="pill-hj">{p.labelHJ}</span>
          <span className="pill-ko">{p.label}</span>
        </button>
      ))}
    </div>
  );
}

// ─── 오행 타일 ───
function OhengTile({ element, info, onClick }) {
  return (
    <div className={'oheng-tile ' + elBgClass(element)} onClick={onClick}>
      <div className={'oheng-hj ' + elClass(element)}>{info.hj}</div>
      <div className="oheng-name">{info.nameKo}({info.hj})</div>
      <div className="oheng-season">{info.season} · {info.direction}</div>
      <div className="oheng-virtue">{info.virtue}</div>
    </div>
  );
}

// ─── Breadcrumb ───
function Breadcrumb({ items }) {
  return (
    <div className="breadcrumb">
      {items.map((it, i) => (
        <React.Fragment key={i}>
          {i > 0 && <span className="bc-sep">›</span>}
          {it.onClick
            ? <a className="bc-link" onClick={(e) => { e.preventDefault(); it.onClick(); }}>{it.label}</a>
            : <span className="bc-current">{it.label}</span>}
        </React.Fragment>
      ))}
    </div>
  );
}

// ─── AdSense 배너 ───
function AdBanner({ style }) {
  const ref = useRef(null);
  useEffect(() => {
    if (ref.current) {
      try { (window.adsbygoogle = window.adsbygoogle || []).push({}); } catch(e) {}
    }
  }, []);
  return (
    <div className="ad-banner" style={style}>
      <ins className="adsbygoogle"
           style={{ display: 'block' }}
           data-ad-client="ca-pub-1690002331948394"
           data-ad-slot="2093396621"
           data-ad-format="auto"
           data-full-width-responsive="true"
           ref={ref} />
    </div>
  );
}

Object.assign(window, {
  elClass, elBgClass, elHJ,
  Brand, Nav, SajuTable, CheonganTile, IljuCard, Footer,
  GenderToggle, IljuPillBar, OhengTile, Breadcrumb, AdBanner,
  fmtDate, fmtDateShort,
});
