// proto-misc.jsx — Study, Music, Project pages

// ── Study (전체 개념도) ─────────────────────────────────────────
function StudyPage() {
  // study/manifest.json 을 fetch → 자료 카드 렌더 (브리핑 latest.json 과 동일 패턴)
  const [state, setState] = React.useState({ items: null, err: null, loading: true });
  React.useEffect(() => {
    let alive = true;
    fetch('study/manifest.json', { cache: 'no-store' })
      .then(r => r.json())
      .then(d => { if (alive) setState({ items: d.materials || [], err: null, loading: false }); })
      .catch(e => { if (alive) setState({ items: null, err: e, loading: false }); });
    return () => { alive = false; };
  }, []);

  return (
    <div className="fade-in">
      <div className="page-h">
        <div className="crumbs">
          <a href="#/">MATE</a>
          <span>/</span>
          <span style={{ color: 'var(--ink-2)' }}>Study</span>
        </div>
        <h1>Study</h1>
        <p className="lead">공부자료 라이브러리 · 자료마다 폴더 하나. 카드를 누르면 해당 자료가 열립니다.</p>
      </div>

      {state.loading && (
        <p className="lead" style={{ marginTop: 24 }}>불러오는 중…</p>
      )}

      {state.err && (
        <div className="card card-pad" style={{ marginTop: 24, borderColor: 'var(--divider)' }}>
          <div className="eyebrow" style={{ color: 'var(--muted)' }}>목록 로드 실패</div>
          <div style={{ marginTop: 6, color: 'var(--ink-2)', fontSize: 14 }}>
            로컬(file://)에서는 보안상 목록을 못 읽습니다. 배포 사이트에서는 정상 표시됩니다.
          </div>
        </div>
      )}

      {state.items && state.items.length === 0 && (
        <p className="lead" style={{ marginTop: 24 }}>아직 올라온 자료가 없어요.</p>
      )}

      {state.items && state.items.length > 0 && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 16, marginTop: 8 }}>
          {state.items.map((m, i) => (
            <a
              key={i}
              href={`study/${m.folder}/${m.entry || 'main.html'}`}
              className="card linkable tint-study card-pad"
              style={{ display: 'block', textDecoration: 'none' }}
            >
              <div className="eyebrow" style={{ color: 'var(--study)' }}>{m.tag || 'STUDY'}</div>
              <div style={{ fontSize: 18, fontWeight: 700, marginTop: 8, letterSpacing: '-0.01em' }}>{m.title}</div>
              {m.date && (
                <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2, fontFamily: 'var(--font-mono)' }}>{m.date}</div>
              )}
              <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 10, lineHeight: 1.5 }}>{m.desc}</div>
              <div style={{ marginTop: 14, fontSize: 13, fontWeight: 600, color: 'var(--study)' }}>열기 →</div>
            </a>
          ))}
        </div>
      )}
    </div>
  );
}

function Architecture() {
  // Diagram laid out with CSS grid + SVG arrows
  return (
    <div style={{ position: 'relative' }}>
      <div className="eyebrow" style={{ marginBottom: 18 }}>아키텍처 · 한 흐름</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 60px 1fr 60px 1fr', alignItems: 'center', gap: 0 }}>
        <DNode title="GitHub" sub="mate-portal repo" body="홈 · 5 카테고리 · 브리핑 HTML" tone="ink" />
        <Arrow label="push" />
        <DNode title="Cloudflare Pages" sub="자동 배포 + CDN" body="push 감지 → 빌드 → 전세계 배포" tone="briefing" />
        <Arrow label="serve" />
        <DNode title="Browser" sub="mate-portal.pages.dev" body="홈에서 5개 코너로 진입" tone="board" />
      </div>

      <div style={{
        margin: '36px 0 18px',
        display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 12,
        color: 'var(--muted)', fontSize: 13,
      }}>
        <span style={{ flex: 1, borderTop: '1px dashed var(--divider)' }} />
        <span>브라우저에서 분기</span>
        <span style={{ flex: 1, borderTop: '1px dashed var(--divider)' }} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12 }}>
        {Object.values(CATS).map(c => (
          <div key={c.key} className={`card tint-${c.key} card-pad`} style={{ textAlign: 'center' }}>
            <CatTag k={c.key} />
            <div style={{ fontSize: 14, fontWeight: 600, marginTop: 8 }}>{c.name}</div>
            <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 4 }}>{c.kor}</div>
          </div>
        ))}
      </div>

      <div style={{
        marginTop: 28, padding: '18px 22px',
        background: 'var(--surface-2)', borderRadius: 'var(--r-sm)',
        display: 'flex', gap: 24, alignItems: 'center', flexWrap: 'wrap',
      }}>
        <div style={{ flex: 1, minWidth: 220 }}>
          <div className="eyebrow" style={{ marginBottom: 6 }}>게시판만 별도</div>
          <div style={{ fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.6 }}>
            게시판은 정적 HTML로 못 푸는 부분이라, <strong>Cloudflare Functions</strong>가 API를 처리하고
            <strong> D1 (SQLite)</strong>에 글/댓글을 저장합니다. <strong>Turnstile</strong>이 봇을 막아요.
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <code style={chip}>POST /api/posts</code>
          <code style={chip}>GET /api/posts</code>
          <code style={chip}>POST /api/comments</code>
          <code style={chip}>D1: posts, comments</code>
        </div>
      </div>
    </div>
  );
}

const chip = {
  fontFamily: 'var(--font-mono)',
  fontSize: 11,
  padding: '4px 8px',
  background: 'var(--surface)',
  border: '1px solid var(--divider)',
  borderRadius: 4,
  color: 'var(--ink-2)',
};

function DNode({ title, sub, body, tone }) {
  const border = tone === 'briefing' ? 'var(--briefing)' : tone === 'board' ? 'var(--board)' : 'var(--ink)';
  return (
    <div className="card card-pad" style={{ borderColor: border, borderWidth: 1.5, textAlign: 'center', minHeight: 120 }}>
      <div className="eyebrow">{sub}</div>
      <div style={{ fontSize: 18, fontWeight: 700, marginTop: 4, letterSpacing: '-0.01em' }}>{title}</div>
      <div style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 8, lineHeight: 1.5 }}>{body}</div>
    </div>
  );
}
function Arrow({ label }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--muted)', letterSpacing: '0.1em', marginBottom: 4, textTransform: 'uppercase' }}>{label}</div>
      <svg width="100%" height="14" viewBox="0 0 60 14">
        <path d="M2 7 L52 7 M46 3 L52 7 L46 11" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round" style={{ color: 'var(--ink-2)' }} />
      </svg>
    </div>
  );
}

// ── Music interstitial ─────────────────────────────────────────
// MusicPage 제거됨 — CATS.music 가 MUSIC_URL로 새 탭 직행.

// ── My Project (About MATE) ─────────────────────────────────────
function ProjectPage() {
  return (
    <div className="fade-in">
      <div className="page-h">
        <div className="crumbs">
          <a href="#/">MATE</a><span>/</span><span style={{ color: 'var(--ink-2)' }}>My Project</span>
        </div>
        <h1>About MATE</h1>
        <p className="lead">Melony AI Trading Engine · 개인 포털 하나로 모든 코너를 묶는 실험. v1.1.</p>
      </div>

      <div className="two-col">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
          <Section title="무엇을">
            <p><strong>MATE</strong>는 <strong>개인 포털</strong>입니다. 공부 노트, 좋아하는 음악, 매일 아침 경제 브리핑, 친구들과의 게시판, 프로젝트 소개 — 다섯 코너를 하나의 입구로 묶었어요. 한 줄로 요약하면 <strong>Melony AI Trading Engine</strong>의 개인 워크스스테이션.</p>
          </Section>
          <Section title="왜">
            <p>흩어진 도구가 너무 많아요. 한 사람을 위한 포털이 있다면 매일 가볍게 들르고, 친구들과 가볍게 이야기 나누고, 어제의 내가 오늘의 나에게 노트를 남길 수 있을 거라 믿었습니다.</p>
          </Section>
          <Section title="어떻게">
            <p>가능한 한 단순하게: <strong>GitHub에 push하면 Cloudflare가 자동 배포</strong>합니다. 정적 사이트이므로 비개발자도 마크다운만 알면 글을 올릴 수 있어요. 게시판만 Cloudflare D1 + Functions로 처리합니다. 브리핑은 맥클(24h 켜진 Mac) 크론이 매일 06:00에 갱신해요.</p>
            <p style={{ marginTop: 12 }}>"<strong>스팸이라도 오는 게 절간보다 낫다</strong>" — Melony CTO의 운영 원칙. 사후 대응으로 갑니다.</p>
          </Section>
          <Section title="앞으로">
            <ul style={{ paddingLeft: 18, margin: 0, lineHeight: 1.9 }}>
              <li>댓글 (이번 주)</li>
              <li>전체 검색 (다음 달)</li>
              <li>커스텀 도메인 (Phase 7)</li>
              <li>다국어 / 다크 모드 (장기)</li>
            </ul>
          </Section>
        </div>

        <aside style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div className="card card-pad">
            <div className="eyebrow" style={{ marginBottom: 12 }}>만든 사람</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <Person nick="Melony" role="CTO · 의사결정" tone="briefing" />
              <Person nick="맥클"   role="자동화 봇 · 24h" tone="study" />
              <Person nick="Claude Code" role="실행 · 코드" tone="board" />
            </div>
          </div>

          <div className="card card-pad" style={{ background: 'var(--surface-2)' }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}>저장소</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.8 }}>
              github.com/melony/<br />
              <span style={{ color: 'var(--briefing)' }}>└ mate-portal</span>
            </div>
            <a className="btn sm" style={{ marginTop: 12 }} href="https://github.com" target="_blank" rel="noopener noreferrer">
              GitHub ↗
            </a>
          </div>

          <div className="card card-pad">
            <div className="eyebrow" style={{ marginBottom: 8 }}>버전</div>
            <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em' }}>v1.1</div>
            <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 4 }}>
              2026. 05. 22 · 게시판을 D1으로 격상
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

function Section({ title, children }) {
  return (
    <div>
      <h2 style={{ fontSize: 18, fontWeight: 700, margin: '0 0 8px', letterSpacing: '-0.01em' }}>{title}</h2>
      <div style={{ fontSize: 15, color: 'var(--ink-2)', lineHeight: 1.7 }}>
        {children}
      </div>
    </div>
  );
}

function Person({ nick, role, tone }) {
  const colors = {
    briefing: { bg: 'var(--briefing-soft)', fg: 'var(--briefing)' },
    study:    { bg: 'var(--study-soft)',    fg: 'var(--study)' },
    board:    { bg: 'var(--board-soft)',    fg: 'var(--board)' },
  }[tone];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <div style={{
        width: 40, height: 40, borderRadius: 8,
        background: colors.bg, color: colors.fg,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontWeight: 700, fontSize: 14,
      }}>{nick.slice(0,1)}</div>
      <div>
        <div style={{ fontWeight: 600 }}>{nick}</div>
        <div style={{ fontSize: 12, color: 'var(--muted)' }}>{role}</div>
      </div>
    </div>
  );
}

Object.assign(window, { StudyPage, ProjectPage });
