// proto-home.jsx — Home (V2 layout: left big Briefing, right 4-card stack)

function HomePage() {
  return (
    <div className="fade-in">
      <PageGreeting />
      <div className="home-grid">
        <BriefingHero />
        <div className="stack">
          <StackCard k="study"   />
          <StackCard k="music"   />
          <StackCard k="board"   />
          <StackCard k="project" />
        </div>
      </div>
      <RecentBoardStrip />
    </div>
  );
}

function PageGreeting() {
  const hr = new Date().getHours();
  const greet = hr < 5 ? '늦은 밤이에요' : hr < 12 ? '좋은 아침이에요' : hr < 18 ? '오후예요' : '저녁이에요';
  return (
    <div style={{ marginBottom: 22 }}>
      <div className="eyebrow" style={{ marginBottom: 6 }}>{todayLabel()}</div>
      <h1 style={{ margin: 0, fontSize: 32, fontWeight: 800, letterSpacing: '-0.025em', lineHeight: 1.15 }}>
        {greet}, <span style={{color: 'var(--briefing)'}}>melony</span>.
      </h1>
      <p style={{ margin: '6px 0 0', color: 'var(--muted)', fontSize: 14 }}>
        오늘의 브리핑이 도착했어요. 5개 코너 어디든 한 클릭이면 됩니다.
      </p>
    </div>
  );
}

// ── Briefing JSON fetcher ────────────────────────────────────────
// /briefing/latest.json 을 fetch. 크론이 매일 함께 출력.
// 로컬 file:// 에서는 CORS로 막힘 — fallback이 정상.
function useBriefingPreview() {
  const [state, setState] = React.useState({ data: null, err: null, loading: true });
  React.useEffect(() => {
    let alive = true;
    fetch('briefing/latest.json', { cache: 'no-store' })
      .then(r => r.ok ? r.json() : Promise.reject(new Error('http ' + r.status)))
      .then(d => { if (alive) setState({ data: d, err: null, loading: false }); })
      .catch(e => { if (alive) setState({ data: null, err: e, loading: false }); });
    return () => { alive = false; };
  }, []);
  return state;
}

// Color a chg string: 빨강=상승(한국 증시 관례)
function dirColor(dir) {
  if (dir === 'up')   return 'var(--up)';
  if (dir === 'down') return 'var(--down)';
  return 'var(--muted)';
}
function dirSymbol(dir) {
  if (dir === 'up')   return '▲';
  if (dir === 'down') return '▼';
  return '·';
}

// ── Left hero: Briefing card (data-driven) ───────────────────────
function BriefingHero() {
  const { data, err, loading } = useBriefingPreview();
  const items = (data?.items || []).slice(0, 4);

  return (
    <a href="briefing/index.html" className="card linkable tint-briefing hero" style={{ textDecoration: 'none' }}>
      <div className="card-pad-lg" style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
        <div className="hero-top">
          <div>
            <CatTag k="briefing" />
            <h2 className="hero-title">
              <span className="accent">오늘의 브리핑</span>
            </h2>
            <div className="hero-meta">
              <span>{data?.generated_at ? `${data.generated_at} 갱신` : todayLabel()}</span>
              <span className="divider-dot" />
              <span>지금 시장 한눈에</span>
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--muted)', letterSpacing: '0.1em' }}>SOURCE</div>
            <div style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 2, fontFamily: 'var(--font-mono)' }}>DART · ECOS · yfinance</div>
          </div>
        </div>

        {loading && (
          <div className="ind-grid" style={{ marginTop: 28, flex: 1 }}>
            {[0,1,2,3].map(i => (
              <div key={i} className="ind">
                <div className="ind-label" style={{ background: 'var(--surface-2)', color: 'transparent' }}>—</div>
                <div className="ind-value" style={{ background: 'var(--surface-2)', color: 'transparent', borderRadius: 4 }}>—</div>
              </div>
            ))}
          </div>
        )}

        {!loading && items.length > 0 && (
          <div className="ind-grid" style={{ marginTop: 28, flex: 1 }}>
            {items.map((it, i) => (
              <div key={i} className="ind">
                <div className="ind-label">{it.label}</div>
                <div className="ind-value">{it.value}</div>
                <div className="ind-chg" style={{ color: dirColor(it.dir) }}>
                  {dirSymbol(it.dir)} {it.chg}
                </div>
              </div>
            ))}
          </div>
        )}

        {!loading && items.length === 0 && (
          <div style={{ marginTop: 28, flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'flex-start', gap: 8 }}>
            <div style={{ fontSize: 18, color: 'var(--ink)', fontWeight: 600 }}>
              {err ? '브리핑 데이터를 못 불러왔어요' : '오늘 브리핑이 아직 갱신 전이에요'}
            </div>
            <div style={{ fontSize: 14, color: 'var(--muted)' }}>
              {err
                ? '로컬 file:// 환경에서는 CORS로 막힐 수 있어요. 전체 브리핑은 정상적으로 열립니다.'
                : '맥클 크론이 06:00에 새 브리핑을 푸시합니다.'}
            </div>
          </div>
        )}

        <div className="hero-foot">
          <span style={{ fontSize: 13, color: 'var(--muted)' }}>
            {data ? `자료원 ${data.items?.length ?? 0}건 · KST` : '맥클 크론이 06:00 자동 게시'}
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontWeight: 600, color: 'var(--briefing)' }}>
            전체 브리핑 보기
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </span>
        </div>
      </div>
    </a>
  );
}

// ── Right stack: 4 category cards ────────────────────────────────
function StackCard({ k }) {
  const c = CATS[k];
  const swatchStyles = {
    study:   { background: 'var(--study-soft)',   color: 'var(--study)' },
    music:   { background: 'var(--music-soft)',   color: 'var(--music)' },
    board:   { background: 'var(--board-soft)',   color: 'var(--board)' },
    project: { background: 'var(--project-soft)', color: 'var(--project)' },
  }[k];

  const counts = {
    study:   '5 모듈',
    music:   '새 탭',
    board:   `${useLivePostCount()} 글`,
    project: 'v1.1',
  }[k];

  // Music = 외부 링크 직행 (인터스티셜 없음)
  const externalProps = c.external
    ? { target: '_blank', rel: 'noopener noreferrer' }
    : {};

  return (
    <a href={c.href} {...externalProps} className={`card linkable tint-${k}`} style={{ textDecoration: 'none' }}>
      <div className="stack-row">
        <div className="icon" style={swatchStyles}>{c.short.slice(0,4)}</div>
        <div className="body">
          <div className="title">{c.name}</div>
          <div className="sub">{c.kor} · {c.blurb}</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div className="eyebrow" style={{ marginBottom: 4 }}>{counts}</div>
          <div className="arrow">
            <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
              <path d="M5 11h12M12 6l5 5-5 5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </div>
        </div>
      </div>
    </a>
  );
}

function useLivePostCount() {
  const posts = usePosts();
  return posts.length;
}

// ── Recent activity strip ────────────────────────────────────────
function RecentBoardStrip() {
  const posts = usePosts();
  const recent = posts.slice(0, 4);
  return (
    <section style={{ marginTop: 40 }}>
      <div className="section-h">
        <h2>최근 게시판</h2>
        <a className="lead" href="#/board" style={{ color: 'var(--ink-2)' }}>전체 보기 →</a>
      </div>
      <div className="card">
        {recent.map((p, i) => (
          <div key={p.id} onClick={() => go(`/board/${p.id}`)} className="post-row"
               style={{ borderBottom: i === recent.length - 1 ? 'none' : undefined,
                        gridTemplateColumns: '70px 1fr 110px 70px 100px' }}>
            <span><span className={`chip tag-${tagClass(p.tag)} active`} style={{ pointerEvents: 'none' }}>{p.tag}</span></span>
            <span className="title-cell">
              <span className="title">{p.title}</span>
              {p.comments?.length > 0 && <span style={{ fontSize: 12, color: 'var(--muted)' }}>· {p.comments.length}</span>}
            </span>
            <span className="nick">{p.nick}</span>
            <span className="num">{p.views ?? 0}</span>
            <span className="time">{relTime(p.ts)}</span>
          </div>
        ))}
      </div>
    </section>
  );
}

function tagClass(tag) {
  return tag === '토론' ? 'discuss' : tag === '질문' ? 'question' : 'chat';
}

Object.assign(window, { HomePage, tagClass });
