/* 念念 — 公开阅读站 应用 */
(function () {
  const { useState, useEffect } = React;
  const h = React.createElement;
  const I = window.NNIcon;
  const D = window.NN;
  const COVER = ['var(--a-write)', 'var(--a-read)', 'var(--a-eng)'];

  const PUB = D.ARTICLES.filter(a => a.status === 'published' && a.visibility === 'public');

  // —— 专题：人工挑选的文章集合 ——
  const TOPICS = [
    { id: 'keep-writing', title: '持续记录这件事', cv: 'var(--a-read)', desc: '关于为什么写、如何坚持，以及记录如何反过来改变了我。', slugs: ['why-keep-a-diary', 'reading-list-2026'] },
    { id: 'build-niannian', title: '把念念搬上网', cv: 'var(--a-write)', desc: '一个只给自己用的工具，如何从桌面应用迁移成个人网站。', slugs: ['from-desktop-to-web'] },
  ];

  function Header({ route, go }) {
    return h('header', { className: 'site-header' },
      h('a', { href: '#/', style: { display: 'flex' } }, h(window.NNLogo, { size: 30, textSize: 17 })),
      h('nav', { className: 'site-nav' },
        h('a', { href: '#/', className: route === 'home' ? 'active' : '' }, '首页'),
        h('a', { href: '#/archive', className: route === 'archive' ? 'active' : '' }, '归档'),
        h('a', { href: '#/topics', className: route === 'topics' || route === 'topic' ? 'active' : '' }, '专题'),
        h('a', { href: 'index.html', className: 'site-login' }, '登录'))
    );
  }

  function ArticleRow({ a, go }) {
    return h('a', { className: 'site-art', href: '#/p/' + a.slug },
      h('div', { className: 'meta tnum' }, a.publishedAt, h('span', null, '·'), a.words + ' 字', h('span', null, '·'), '约 ' + Math.max(1, Math.round(a.words / 400)) + ' 分钟'),
      h('h2', null, a.title),
      h('p', null, a.excerpt),
      h('div', { className: 'tags' }, a.tags.map(tg => h(window.NNTag, { key: tg, name: tg, color: (D.TAGS.find(x => x.name === tg) || {}).color })))
    );
  }

  function Home({ go }) {
    return h('div', null,
      h('div', { className: 'site-main' },
        h('div', { className: 'site-hero' },
          h('div', { className: 'seal' }, '念'),
          h('h1', null, D.SITE.name),
          h('p', null, D.SITE.intro)),
        h('div', { className: 'site-sec-label' }, h('span', null, '最新发布'), h('div', { className: 'line' })),
        h('div', { className: 'site-list' }, PUB.map(a => h(ArticleRow, { key: a.id, a, go }))),
        h('div', { className: 'site-sec-label', style: { marginTop: 18 } }, h('span', null, '专题'), h('div', { className: 'line' })),
        h('div', { className: 'site-topic-grid' }, TOPICS.map(t => h('a', { key: t.id, className: 'site-topic-card', href: '#/t/' + t.id },
          h('div', { className: 'site-topic-cover', style: { '--cv': t.cv } }, h('h3', null, t.title)),
          h('div', { className: 'site-topic-body' }, h('p', null, t.desc), h('span', { className: 'cnt' }, t.slugs.length + ' 篇文章')))))
      ),
      h(Footer)
    );
  }

  function Archive({ go }) {
    const [tag, setTag] = useState('全部');
    const tags = ['全部', ...new Set(PUB.flatMap(a => a.tags))];
    const list = tag === '全部' ? PUB : PUB.filter(a => a.tags.includes(tag));
    return h('div', null,
      h('div', { className: 'site-main' },
        h('div', { className: 'site-hero', style: { padding: '64px 0 36px' } },
          h('h1', { style: { fontSize: 32 } }, '文章归档'),
          h('p', null, `共 ${PUB.length} 篇公开文章`)),
        h('div', { className: 'site-chips' }, tags.map(tg => h('button', { key: tg, className: 'nn-chip' + (tag === tg ? ' active' : ''), onClick: () => setTag(tg) }, tg))),
        h('div', { className: 'site-list' }, list.map(a => h(ArticleRow, { key: a.id, a, go })))
      ),
      h(Footer)
    );
  }

  function Article({ slug, go }) {
    const idx = PUB.findIndex(a => a.slug === slug);
    const a = PUB[idx] || PUB[0];
    const prev = PUB[idx - 1], next = PUB[idx + 1];
    useEffect(() => { window.scrollTo(0, 0); }, [slug]);
    return h('div', null,
      h('div', { className: 'site-main' },
        h('article', { className: 'site-article' },
          h('a', { className: 'back', href: '#/archive' }, I('arrowL', { size: 15 }), '返回归档'),
          h('div', { className: 'a-meta tnum' }, a.publishedAt, h('span', null, '·'), a.words + ' 字', h('span', null, '·'), '约 ' + Math.max(1, Math.round(a.words / 400)) + ' 分钟'),
          h('h1', null, a.title),
          h('div', { className: 'a-tags' }, a.tags.map(tg => h(window.NNTag, { key: tg, name: tg, color: (D.TAGS.find(x => x.name === tg) || {}).color }))),
          a.cover ? h('div', { className: 'site-cover', style: { '--cv': COVER[a.cover - 1] || COVER[0] } }, h('span', null, 'COVER · 封面图占位')) : null,
          h('div', { className: 'site-prose' },
            a.body.split('\n').filter(Boolean).map((p, i) => p.startsWith('## ') ? h('h2', { key: i }, p.slice(3)) : h('p', { key: i }, p))),
          h('div', { className: 'site-end' }, '· 念 ·'),
          h('div', { className: 'site-pn' },
            prev ? h('a', { href: '#/p/' + prev.slug }, h('div', { className: 'dir' }, '← 上一篇'), h('div', { className: 't' }, prev.title)) : h('span', { style: { flex: 1 } }),
            next ? h('a', { href: '#/p/' + next.slug, className: 'next' }, h('div', { className: 'dir' }, '下一篇 →'), h('div', { className: 't' }, next.title)) : h('span', { style: { flex: 1 } }))
        )
      ),
      h(Footer)
    );
  }

  function Topics({ go }) {
    return h('div', null,
      h('div', { className: 'site-main' },
        h('div', { className: 'site-hero', style: { padding: '64px 0 30px' } },
          h('h1', { style: { fontSize: 32 } }, '专题'),
          h('p', null, '按主题重新组织的阅读集合。')),
        h('div', { className: 'site-topic-grid' }, TOPICS.map(t => h('a', { key: t.id, className: 'site-topic-card', href: '#/t/' + t.id },
          h('div', { className: 'site-topic-cover', style: { '--cv': t.cv } }, h('h3', null, t.title)),
          h('div', { className: 'site-topic-body' }, h('p', null, t.desc), h('span', { className: 'cnt' }, t.slugs.length + ' 篇文章'))))) ),
      h(Footer));
  }

  function Topic({ id, go }) {
    const t = TOPICS.find(x => x.id === id) || TOPICS[0];
    const arts = t.slugs.map(s => PUB.find(a => a.slug === s)).filter(Boolean);
    useEffect(() => { window.scrollTo(0, 0); }, [id]);
    return h('div', null,
      h('div', { className: 'site-main' },
        h('a', { className: 'back', href: '#/topics', style: { display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 18, color: 'var(--text-3)', fontSize: 14 } }, I('arrowL', { size: 15 }), '全部专题'),
        h('div', { className: 'site-topic-cover', style: { '--cv': t.cv, borderRadius: 'var(--radius-lg)', aspectRatio: '16/5', marginBottom: 14 } }, h('h3', { style: { fontSize: 26 } }, t.title)),
        h('p', { style: { fontSize: 15, color: 'var(--text-3)', maxWidth: '62ch', margin: '0 0 14px' } }, t.desc),
        h('div', { className: 'site-sec-label' }, h('span', null, '本专题文章'), h('div', { className: 'line' })),
        h('div', { className: 'site-list' }, arts.map(a => h(ArticleRow, { key: a.id, a, go })))),
      h(Footer));
  }

  function Footer() {
    return h('footer', { className: 'site-footer' },
      h('div', { style: { marginBottom: 8 } }, '念念 · 一个人的记录、阅读与写作'),
      h('div', null, '© 2026 · ', h('a', { href: 'index.html' }, '进入后台')));
  }

  function parse() {
    const hh = (location.hash || '').replace(/^#\/?/, '');
    if (hh.startsWith('p/')) return { route: 'article', slug: hh.slice(2) };
    if (hh.startsWith('t/')) return { route: 'topic', id: hh.slice(2) };
    if (hh === 'topics') return { route: 'topics' };
    if (hh === 'archive') return { route: 'archive' };
    return { route: 'home' };
  }

  function App() {
    const [st, setSt] = useState(parse());
    useEffect(() => {
      const on = () => setSt(parse());
      window.addEventListener('hashchange', on);
      return () => window.removeEventListener('hashchange', on);
    }, []);
    const go = (r) => { location.hash = r; };
    return h('div', { className: 'site-body' },
      h(Header, { route: st.route, go }),
      st.route === 'home' ? h(Home, { go })
        : st.route === 'archive' ? h(Archive, { go })
        : st.route === 'topics' ? h(Topics, { go })
        : st.route === 'topic' ? h(Topic, { id: st.id, go })
        : h(Article, { slug: st.slug, go })
    );
  }

  window.NNApplyTheme(window.NNReadTheme());
  ReactDOM.createRoot(document.getElementById('root')).render(h(App));
})();
